有没有一种方法可以将变量传递给Django中的“扩展"模板? [英] Is there a way to pass a variable to an 'extended' template in Django?
问题描述
我想为布局模板添加一些灵活性,但是找不到任何方法.
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?
推荐答案
我怀疑 block
是您首先要寻找的东西.
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%}
在您的子模板上:
{% extends 'layout.html' %}
{% block sidebar_wrapper %}
{% with sidebar=True sidebar_width=4 %}
{{ block.super }}
{% endwith%}
{% endblock sidebar_wrapper%}
这篇关于有没有一种方法可以将变量传递给Django中的“扩展"模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!