djangodjango-inheritance

Django {% include %} tag displays hardcorded string but not variable


I want one template to inherit a variable from another template using the Django {% include %} tag. But it's not happening.

section.html, the template to inherit from:

{% block section1 %}
<p>My cows are home.</p>
--> {{ word_in_template }} <--
{% endblock %}

index.html, which should inherit word_in_template from section.html:

{% include "section.html" with word_in_template=word_in_template %}

I've also tried {% include "section.html" with word_in_template=word %}.

My view:

def myblog(request):
    return render_to_response('index.html')

def section(request):
    word = "frisky things."
    return render_to_response('section.html', {'word_in_template':word})

Output for section.html in Chrome:

My cows are home.

--> frisky things. <--

Output for index.html in Chrome:

My cows are home.

--> <--

I'm following this solution but it doesn't work for me. "frisky things" shows if I load section.html but it doesn't show on index.html. However, the hardcoded string My cows are home shows up on index.html.

I think I'm following the documentation right too. But I'm new so maybe I'm not reading things right or something. What am I doing wrong?


Solution

  • When you include section.html in your index.html template, it doesn't automatically include the context from the section view. You need to include the context in the myblog view.

    def myblog(request):
        word = "my_word"
        return render(request, 'index.html', {'word_in_template':word}))
    

    In the template, the correct way to do the include is word_in_template=word_in_template, since word_in_template is the key in the context dictionary.

    {% include "section.html" with word_in_template=word_in_template %}