Is there any way to reuse template tag value in Django templates?
For example, let's say there is a custom template tag
{% custom_tag "parameter" %}
This tag requires some serious database work to calculate.
Now I need to have something like that (pseudocode):
if {% custom_tag "parameter" %}
....
else
....
I know that with context variables I can do just:
{% with variable.x.y.z as v %}
{% if v %}
Blah-Blah-Blah {{ v }}
{% else %}
No value
{% endif %}
{% endwith %}
But is there any way do achieve this with template tag val开发者_JAVA百科ue?
EDIT: The only option I've came up with so far is to make a filter out of my template tag:
{% if "parameter" | custom_tag %}
Blah {{ "parameter" | custom_tag }}
{% else %}
....
{% endif %}
But this option makes custom_tag execute twice, and that's not good performance-wise
i haven't test it but i guess that you can add a variable to the context from your custom tag.. maybe this will help you http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#setting-a-variable-in-the-context
I believe you can assign the results of filtering to a variable and use it. This way the filter will only get called once. From the docs: with: Caches a complex variable under a simpler name. This is useful when accessing an "expensive" method (e.g., one that hits the database) multiple times.
{% with "parameter" | custom_tag as result %}
{% if result %}
Blah {{ result }}
{% else %}
....
{% endif %}
{% endwith %}
精彩评论