开发者

Django: avoiding multiple evaluations of the same expression in a template?

When passing an object called widget开发者_StackOverflow as part of the context to rendering a django template, I may have a method which is a bit expensive, but I want to display the result of it more than once.

Python:

class Widget:
   def work(self):
      # Do something expensive

Template

This is a widget, the result of whose work is {{widget.work}}.  Do
you want to save {{widget.work}} or discard {{widget.work}}?

Clearly I could work around this by evaluating the method once in the view code, and then passing the result in, but this seems to couple the view and the template too much. Is there a way for the template author to stash values for re-use later in the template? I would like to do something like this:

{% work_result = widget.work %}
This is a widget, the result of whose
work is {{work_result}}.  Do you want to save {{work_result}} or discard {{work_result}}?

Does such a construct exist in the django template language?


{% with %}


{% with work_result=widget.work %}

Look Django docs for more information

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜