gpt4 book ai didi

django - 是否有让我设置上下文变量的Django模板标签?

转载 作者:行者123 更新时间:2023-12-03 22:48:53 24 4
gpt4 key购买 nike

我希望能够将模板中的变量设置为字符串值。我写了一个标签,但是它似乎并没有改变上下文。预期用途是:

{% define "a string" as my_var %}


更新(已解决):

class DefineNode(Node):
def __init__(self, var, name):
self.var = var
self.name = name

def __repr__(self):
return "<DefineNode>"

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

@register.tag
def define(parser, token):
"""
Adds a name to the context for referencing an arbitrarily defined string.

For example:

{% define "my_string" as my_string %}

Now anywhere in the template:

{{ my_string }}
"""
bits = list(token.split_contents())
if (len(bits) != 4 or bits[2] != "as") or \
not (bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]):
raise TemplateSyntaxError("%r expected format is '\"string\" as name'" % bits[0])
else:
value = bits[1][1:-1]
name = bits[3]
return DefineNode(value, name)

最佳答案

您无需编写自己的标签。内置的{% with %}标记执行此操作。

关于django - 是否有让我设置上下文变量的Django模板标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2566265/

24 4 0