Is there a way to pass a variable to an 'extended' template in Django?

别等时光非礼了梦想. 提交于 2020-11-30 08:11:44

问题


I want to add some flexibility to my layout template, but I can't find any way to do so.

I'm looking for a way to extend my layout template with variable, i.e. to pass a variable up in the template tree, not down.

# views.py
def my_view_func(request):
    return render(request, "child.html")

# child.html
{% extends 'layout.html' with show_sidebar=True sidebar_width_class="width_4" %}

<div>Templates stuff here</div>

# layout.html
{% if show_sidebar %}
    <div class="{{ sidebar_width_class }}">
        {% block sidebar %}{% endblock %}
    </div>
{% endif %}

I have to maintain four templates with a difference in a few lines of code. For example, I have two templates that differ from each other by a sidebar width class. Am I doing something wrong?


回答1:


I suspect that block is what you are looking for in the first place.

Form your block inside the base template like this:

{% block sidebar_wrapper %}
    {% if sidebar %}
    <div class="width{{sidebar_width}}">
        {% block sidebar %}{% endblock %}
    </div>
    {% endif %}
{% endblock sidebar_wrapper%}

And on your child template:

{% extends 'layout.html' %}
{% block sidebar_wrapper %}
    {% with sidebar=True sidebar_width=4 %}
        {{ block.super }}
    {% endwith%}
{% endblock sidebar_wrapper%}



回答2:


What you need is an include template tag. You can include a template in another template and render that with specific context.

{% include 'layout.html' with sidebar=True sidebar_width=4 %}

Check docs here: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include



来源:https://stackoverflow.com/questions/36963802/is-there-a-way-to-pass-a-variable-to-an-extended-template-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!