Claudiu Creanga
Claudiu Creanga

Reputation: 8366

Method get_context_data is called twice when using template tags in django

I have a template_tag.py:

from django import template

from myapp.views import RenderView

register = template.Library()

@register.inclusion_tag("template_tag.html")
def render_myapp():
    rv=RenderView()
    return rv.get_context_data()

and myapp.views.py:

from django.views.generic.base import TemplateView
class RenderView(TemplateView):
    template_name = "test.html"

    def get_context_data(self, **kwargs):
        context = super(RenderView, self).get_context_data(**kwargs)
        context["test"] = 1 # this is hit twice in the debugger

        return context

template_tag.html:

{% if test %}
    {{ test|safe }}
{% endif %}

base.html (different app):

{% load template_tag %}
{% render_myapp %}

I wonder why RenderView().get_context_data() is hit twice in the debugger? I don't call it twice in my template. It's probably because TemplateView already calls get_context_data and then I call it again rv.get_context_data(). But then how should my template_tag.py look like to not call get_context_data() again?

Upvotes: 0

Views: 603

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599866

There seem to be two situations here.

In one case, the template tag is always in a template that is rendered by your RenderView. In which case, there doesn't seem to be any need for a tag; you should just either include template_tag.html or put its code directly into test.html.

In the other case, the tag is in another template, or in a range of templates that may or may not be rendered by RenderView. In which case, why is the context data for that page defined in RenderView? It should be defined directly in render_myapp().

Upvotes: 2

Related Questions