[英]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.