【问题标题】:Django simple_tag and setting context variablesDjango simple_tag 和设置上下文变量
【发布时间】:2011-06-22 11:55:34
【问题描述】:

我正在尝试使用 simple_tag 并设置上下文变量。我正在使用 django 的主干版本

from django import template

@register.simple_tag(takes_context=True)
def somefunction(context, obj):   
    return set_context_vars(obj)

class set_context_vars(template.Node):
    def __init__(self, obj):
        self.object = obj

    def render(self, context):
        context['var'] = 'somevar'
        return ''

这不会设置变量,但如果我用@register.tag 做一些非常相似的事情,它可以工作,但对象参数不会通过......

谢谢!

【问题讨论】:

    标签: django templates tags


    【解决方案1】:

    您在这里混合了两种方法。 simple_tag 只是一个辅助函数,它减少了一些样板代码并应该返回一个字符串。要设置上下文变量,您需要(至少使用普通 django)使用 render 方法将 write your own tag 设置为。

    from django import template
    
    register = template.Library()
    
    
    class FooNode(template.Node):
    
        def __init__(self, obj):
            # saves the passed obj parameter for later use
            # this is a template.Variable, because that way it can be resolved
            # against the current context in the render method
            self.object = template.Variable(obj)
    
        def render(self, context):
            # resolve allows the obj to be a variable name, otherwise everything
            # is a string
            obj = self.object.resolve(context)
            # obj now is the object you passed the tag
    
            context['var'] = 'somevar'
            return ''
    
    
    @register.tag
    def do_foo(parser, token):
        # token is the string extracted from the template, e.g. "do_foo my_object"
        # it will be splitted, and the second argument will be passed to a new
        # constructed FooNode
        try:
            tag_name, obj = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0]
        return FooNode(obj)
    

    这可以这样调用:

    {% do_foo my_object %}
    {% do_foo 25 %}
    

    【讨论】:

    • 请注意,Django 的开发版本包含assignment_tag,它类似于simple_tag,但实现了as variablenamedocs.djangoproject.com/en/dev/howto/custom-template-tags/…
    • 嗯,我以前从没遇到过assignment_tag。漂亮。面向未来读者的更新:assignment_tag 可用于 Django 版本 >= 1.4(我假设在进行上述评论时它在 dev 中)。
    • 现在可以使用as variable 保存simple_tag 结果,并且不推荐使用assignment_tag
    • 来自文档: assignment_tag 自 1.9 版起已弃用。 simple_tag 现在可以将结果存储在模板变量中,应改为使用。 docs.djangoproject.com/en/1.11/howto/custom-template-tags/…
    【解决方案2】:

    从 Django 1.9 开始,it is possible 存储 simple_tag 通过使用 as 参数后跟变量名来生成模板变量:

    @register.simple_tag
    def current_time(format_string):
        return datetime.datetime.now().strftime(format_string)
    
    {% current_time "%Y-%m-%d %I:%M %p" as the_time %}
    <p>The time is {{ the_time }}.</p>
    

    【讨论】:

    • 谢谢,我已经搜索了好几个小时了!它适用于 Django 3.0
    • 很高兴它有帮助:)!
    猜你喜欢
    • 2012-04-16
    • 2012-03-05
    • 2016-12-25
    • 2020-12-04
    • 2014-08-15
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多