动态选择django包含标签的模板

Dou*_*ris 9 django django-templates

目前

我有一个包含标记,编码如下:

@register.inclusion_tag('forms/my_insert.html', takes_context=True)
def my_insert(context):
    # set up some other variables for the context
    return context
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我通过放入包含它 {% my_insert %}

新功能请求

我们现在想要测试一个新的布局 - 它只是对模板的更改,而不是对上下文变量的更改.我通过拨打第一个来完成这个

@register.inclusion_tag('forms/my_new_insert.html', takes_context=True)
def my_new_insert(context):
    return my_insert(context)
Run Code Online (Sandbox Code Playgroud)

要使用新模板,我必须使用:

{% ifequal some_var 0 %}
    {% my_insert %}
{% endifequal %}
{% ifnotequal some_var 0 %}
    {% my_new_insert %}
{% endifnotequal %}
Run Code Online (Sandbox Code Playgroud)

问题

有没有办法在函数中选择设置模板标签上下文的模板?

它可能是这样的:

@register.inclusion_tag('forms/my_insert.html', takes_context=True)
def my_insert(context):
    # set up some other variables for the context
    if context['some_var'] == 0:
        context['template'] = 'forms/my_insert.html'
    else:
        context['template'] = 'forms/my_new_insert.html'
    return context
Run Code Online (Sandbox Code Playgroud)

小智 1

您需要创建自己的自定义标签,其参数将作为您的模板。没有办法将包含标签与多个模板一起使用。