Django simple_tag和设置上下文变量

neo*_*ser 10 tags django templates

我试图使用simple_tag并设置上下文变量.我正在使用django的trunk版本

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 ''
Run Code Online (Sandbox Code Playgroud)

这不设置变量,但是如果我做了一些与@register.tag它非常相似的工作但是对象参数没有通过...

谢谢!

Rei*_*cke 19

你在这里混合两种方法.A simple_tag只是一个辅助函数,它减少了一些样板代码并且应该返回一个字符串.要设置上下文变量,您需要(至少使用plain django)使用render方法编写自己的标记.

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)
Run Code Online (Sandbox Code Playgroud)

这可以像这样调用:

{% do_foo my_object %}
{% do_foo 25 %}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,Django的开发版本包含`assignment_tag`,类似于`simple_tag`但实现了`as variablename`:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment标签都有效 (6认同)
  • 现在可以使用`as variable`保存`simple_tag`结果,并且不推荐使用`assignment_tag`. (3认同)

mrt*_*rts 10

从 Django 1.9 开始,可以通过使用参数后跟变量名来将结果存储simple_tag在模板变量中:as

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

  • 谢谢,我已经找这个好几个小时了!它适用于 Django 3.0 (4认同)