簡體   English   中英

在Django模板中使用雙星號運算符

[英]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=11 as foo符號。

因此,您有三個選擇:

1)包含的模板將具有頂級模板中所有可用的變量。 主要timewindow.htmltimewindow.htmlsearch_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM