Django simple_标记和设置上下文变量
我试图使用一个简单的_标记并设置一个上下文变量。我使用的是django的主干版本Django simple_标记和设置上下文变量,django,templates,tags,Django,Templates,Tags,我试图使用一个简单的_标记并设置一个上下文变量。我使用的是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):
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_标记
仅仅是一个助手函数,它减少了一些样板代码,并且应该返回一个字符串。要设置上下文变量,您需要(至少对于普通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)
这可以这样称呼:
{% do_foo my_object %}
{% do_foo 25 %}
自Django 1.9以来,要存储simple_标记
将使用as
参数和变量名生成模板变量:
@register.simple\u标签
定义当前时间(格式字符串):
return datetime.datetime.now().strftime(格式\字符串)
{%current\u time”%Y-%m-%d%I:%m%p“作为\u time%}
时间是{{The_time}}
请注意,Django的开发版本包括assignment\u tag
,它类似于simple\u tag
,但实现了作为variablename
:嗯,我以前从未遇到过assignment\u tag
。漂亮。面向未来读者的更新:assignment\u tag
可在Django版本>=1.4中使用(我假设在上面发表评论时,它在dev中).现在可以使用作为变量保存simple_标记
结果
,并且assignment_标记
已被弃用。从文档中可以看出:assignment_标记自1.9版起已被弃用。simple_标记现在可以将结果存储在模板变量中,应该改用它。谢谢,我已经找了好几个小时了!它适用于Django 3.0很高兴它有帮助:)!