简体   繁体   English

在Django模板中使用双星号运算符

[英]use double asterisk operator in django templates

I'd like to provide some extra templates for my base template to include, just like the following code: 我想为基本模板提供一些额外的模板,就像下面的代码一样:

views : 意见

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 base.html

{% for extra_template in extras %}
  {% include extra_template.path %}
{% endfor %}

I think this can be more powerful, if I can also provide some keyword arguments and use them as context when rendering the extra templates, but I couldn't do it, the following code doesn't work : 我认为,如果我还可以提供一些关键字参数并将它们用作渲染额外模板时的上下文,那么它可能会更强大,但是我做不到,以下代码不起作用

views : 意见

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 base.html

{% for extra_template in extras %}
  {% include extra_template.path with extra_template.context %}
{% endfor %}

If I could use something like the ** operator inside a django template, that would allow some very awesome code reusage. 如果我可以在django模板中使用类似**运算符的东西,那将允许一些非常出色的代码重用。

First, You can not use double asterisks in include tag. 首先,您不能在include标记中使用双星号。 include tag's with parameter only understands foo=1 or 1 as foo notations. include标记的with参数只能理解foo=11 as foo符号。

So, you have three options: 因此,您有三个选择:

1) Included template will have all variables available from top level template. 1)包含的模板将具有顶级模板中所有可用的变量。 Main con: timewindow.html and search_box.html can't have same variable with different values. 主要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) Use prefix 2)使用前缀

{# parent template #}
{% for extra_template in extras %}
    {% include extra_template.path with extra=extra_template.context %}
{% endfor %}

{# included template #}
{{ extra.var }}

3) Write custom template tag and expand context by yourself 3)编写自定义模板标签并自行扩展上下文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM