我正在尝试使用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
做一些非常类似的事情,它可以工作,但是对象参数不会通过...
谢谢!
您正在混合两种方法。 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 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>