gpt4 book ai didi

python - Django simple_tag 和设置上下文变量

转载 作者:行者123 更新时间:2023-12-02 10:58:35 25 4
gpt4 key购买 nike

我正在尝试使用 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 ''

这不会设置变量,但如果我对 @register.tag 执行非常类似的操作,它会起作用,但对象参数不会传递...

谢谢!

最佳答案

您在这里混合了两种方法。 simple_tag 只是一个辅助函数,它减少了一些样板代码,并且应该返回一个字符串。要设置上下文变量,您需要(至少对于普通的 django)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 %}

关于python - Django simple_tag 和设置上下文变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4917515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com