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

时间:2010-10-14 21:22:17

标签: 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

在我的模板中,我通过输入{% my_insert %}

来加入它

新功能请求

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

来完成这项工作
@register.inclusion_tag('forms/my_new_insert.html', takes_context=True)
def my_new_insert(context):
    return my_insert(context)

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

{% ifequal some_var 0 %}
    {% my_insert %}
{% endifequal %}
{% ifnotequal some_var 0 %}
    {% my_new_insert %}
{% endifnotequal %}

问题

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

想象它可能是这样的:

@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

3 个答案:

答案 0 :(得分:3)

我必须管理上面的相同问题,我这样解决了:

dummy.html

{% extends template %}

mytags.py

from django.template import Library

register = Library()

@register.inclusion_tag('dummy.html')
def render_sample(template='default.html'):
    return {'template': template}

的layout.html

{% load mytags %}

{% render_sample template="another_template.html"

答案 1 :(得分:1)

您需要使用参数创建自己的自定义标记,该参数将作为您的模板。哪里无法使用带有多个模板的包含标记。

答案 2 :(得分:0)

试试这个:

@register.inclusion_tag('include/dummy.html')
def my_new_insert(template='forms/my_insert.html'):
    return {'template': template,
            'myvar': Myobject.objects.all()}

并查看django documentation