繁体   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