[英]use double asterisk operator in django templates
我想为基本模板提供一些额外的模板,就像下面的代码一样:
意见 :
def my_view(request):
extra_templates=[
{'path': 'dashboard/timewindow.html'},
{'path': 'dashboard/search_box.html'},
]
context = {'extras': extra_templates}
return render(request, 'dashboard/base.html', context)
base.html
{% for extra_template in extras %}
{% include extra_template.path %}
{% endfor %}
我认为,如果我还可以提供一些关键字参数并将它们用作渲染额外模板时的上下文,那么它可能会更强大,但是我做不到,以下代码不起作用 :
意见 :
def my_view(request):
extra_templates=[
{'path': 'dashboard/timewindow.html', 'context': {'var': 23}},
{'path': 'dashboard/search_box.html'},
]
context = {'extras': extra_templates}
return render(request, 'dashboard/base.html', context)
base.html
{% for extra_template in extras %}
{% include extra_template.path with extra_template.context %}
{% endfor %}
如果我可以在django模板中使用类似**
运算符的东西,那将允许一些非常出色的代码重用。
首先,您不能在include
标记中使用双星号。 include
标记的with
参数只能理解foo=1
或1 as foo
符号。
因此,您有三个选择:
1)包含的模板将具有顶级模板中所有可用的变量。 主要timewindow.html
: timewindow.html
和search_box.html
不能具有不同值的相同变量。
def my_view(request):
extra_templates=[
{'path': 'dashboard/timewindow.html'},
{'path': 'dashboard/search_box.html'},
]
context = {'extras': extra_templates, 'var': 23}
return render(request, 'dashboard/base.html', context)
2)使用前缀
{# parent template #}
{% for extra_template in extras %}
{% include extra_template.path with extra=extra_template.context %}
{% endfor %}
{# included template #}
{{ extra.var }}
3)编写自定义模板标签并自行扩展上下文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.