gpt4 book ai didi

python - 有权访问 Context 的 Jinja 扩展

转载 作者:太空狗 更新时间:2023-10-30 00:32:07 24 4
gpt4 key购买 nike

是否可以编写一个 Jinja2 扩展,在渲染时可以访问模板上下文?我想编写一个扩展来访问上下文变量并根据该变量输出一些数据。我找不到有关如何编写此类扩展的足够信息。

现在,我有这个:

class CsrfExtension(jinja2.ext.Extension):
r""" Adds a {% csrf %} tag to Jinja. """

tags = set(['csrf'])
template = '<input type="hidden" name="csrfmiddlewaretoken" value="%s">'

def parse(self, parser):
token = next(parser.stream)
lineno = token.lineno
return self.call_method('_render_csrf', lineno=lineno)

def _render_csrf(self, value, name, *args, **kwargs):
csrf_token = somehow_get_variable('csrf_token')
return jinja2.Markup(self.template % csrf_token)

但是,在 foo.jinja

<!DOCTYPE html>
<html>
<body>
<h1>This is a Test</h1>
{% csrf %}
</body>
</html>

我明白了

SyntaxError at /
invalid syntax (foo.jinja, line 7)

我以为我会得到一个 NameError,因为 somehow_get_variable() 没有定义。我需要知道 a) 如何从当前上下文中获取变量,以及 b) 如何正确编写扩展。

此外,为什么是第 7 行? {% csrf %} 标签在第 5 行。即使我将 foo.jinja 修剪为只有一行 {% csrf %} code> 标签,它表示第 7 行。

最佳答案

找到了。似乎 Jinja 从 Jinja AST(?)生成 Python 代码并且转换失败,因此导致了 SyntaxError。 jinja2.nodes.ContextReference() 可用于获取渲染上下文。

class CsrfExtension(jinja2.ext.Extension):
r""" Adds a {% csrf %} tag to Jinja. """

tags = set(['csrf', 'csrf_token'])
template = u'<input type="hidden" name="csrfmiddlewaretoken" value="%s">'

def parse(self, parser):
lineno = next(parser.stream).lineno
ctx_ref = jinja2.nodes.ContextReference()
node = self.call_method('_render_csrf', [ctx_ref], lineno=lineno)
return jinja2.nodes.CallBlock(node, [], [], [], lineno=lineno)

def _render_csrf(self, context, caller):
csrf_token = context['csrf_token']
return jinja2.Markup(self.template % unicode(csrf_token))

csrf = CsrfExtension

关于python - 有权访问 Context 的 Jinja 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170013/

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