【问题标题】:Inheriting context variables inside custom template tags在自定义模板标签中继承上下文变量
【发布时间】:2013-02-14 10:54:56
【问题描述】:

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

我想在呈现myTemplate.html 的自定义模板标签内使用myVar

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

【问题讨论】:

标签: python django django-templates


【解决方案1】:

使用 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)

passing variables to the templatetag:

要使用变量类,只需将其实例化为 要解析的变量,然后调用 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异常 在页面的当前上下文中添加到它。

也可能有用:setting a variable in the context

【讨论】:

  • 感谢您精心设计和深思熟虑的回复!它帮助我完美地解决了我的问题。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2015-01-20
    • 2014-03-04
    • 1970-01-01
    • 2014-01-15
    相关资源
    最近更新 更多