0

我有一个带有上下文变量的 django 模板myVar,在视图函数中设置。该模板还呈现了一个自定义的简单模板标签{% myTemplateTag %},该标签呈现myTemplate.html

我想myVar在呈现myTemplate.html.

有没有办法在自定义模板标签中继承我的视图函数的上下文变量?(没有将它作为参数显式传递给模板标签)?

4

2 回答 2

2

使用 simple_tag

使用simple_tag,只需设置takes_context=True

@register.simple_tag(takes_context=True)
def current_time(context, format_string):
    timezone = context['timezone']
    return your_get_current_time_method(timezone, format_string)

使用自定义模板标签

只需使用 template.Variable.resolve(),即。

foo = template.Variable('some_var').resolve(context)

请参阅将变量传递给 templatetag

要使用Variable 类,只需使用要解析的变量名称对其进行实例化,然后调用variable.resolve(context)。因此,例如:

class FormatTimeNode(template.Node):
    def __init__(self, date_to_be_formatted, format_string):
        self.date_to_be_formatted = template.Variable(date_to_be_formatted)
        self.format_string = format_string

    def render(self, context):
        try:
            actual_date = self.date_to_be_formatted.resolve(context)
            return actual_date.strftime(self.format_string)
        except template.VariableDoesNotExist:
            return ''

如果变量解析在页面的当前上下文中无法解析传递给它的字符串,它将引发 VariableDoesNotExist 异常。

也可能有用:在 context 中设置一个变量

于 2013-02-14T11:01:39.557 回答
0

也许您可以文件而不是include使用myTemplate.html特殊标签呈现它?你看过包含标签吗?如果你include myTemplate.html它将与包含它的人共享上下文。

于 2013-02-14T11:01:47.337 回答