django-templatesdjango-custom-tags

does it template tag in django execute twice?


If I put in django template.html this code

<p>{% if some_custom_template %} {%some_custom_template%} {% else %} nothing {% endif %}</p>

will some_custom_template executed twice? Or some_custom_template result is buffered?

If some_custom_template is executed twice, how I can save first result in some template variable?


Solution

  • I believe it will be executed twice, but it depends on what some_custom_template actually is. But regardless, you can cache it using the with template tag

    {% with cached_template=some_custom_template %}</p>
        <p>
           {% if cached_template %}
             {{ cached_template }}
           {% else %}
              nothing
           {% endif %}
        </p>
    {% endwith %}
    

    Edit: With context, you are using a custom template_tag, which is very different. Yes they are generated every time you call them, and they cannot be cached.

    What would be better is to move the logic of what to display into the template tag and remove the if/then/else in the template, like so:

    @simple_tag(name='unread_notification_count', takes_context=True)
    def unread_notification_count(context):
      if some_check:
        return some_value
      else:
        return "nothing"
    

    Then in the template just have the template tag call:

    <p>{% unread_notification_count %}</p>