views:

40

answers:

2

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 value?

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

+1  A: 

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

pleasedontbelong
Unfortunately, I have to use templatetag with a parameter, so I can't really create a context variable for that :(
xyzman
well i still think that your answer is in the link i posted, if you look in their exemple, they also pass a parameter to the custom tag and in the end they create a variable that can be used on the rest of the template. So i guess you could do something like: {% custom_tag "parameter" %}{% if response %} bla bla{% else %} bla blaAssuming that "response" is the variable created on the custom tag
pleasedontbelong
Thanks for the idea. I've defined my custom tag that sets a context variable inside it. Just see "do_with" in django template/defaulttags.py for an example.
xyzman
A: 

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 %}
Manoj Govindan