gpt4 book ai didi

python - Mako 模板变量名称

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

是否可以在渲染前获取 Mako 模板中变量的名称?

from mako.template import Template
bar = Template("${foo}")

# something like:
# >> print bar.fields()
# ['foo']

用例:

我们有配置文件,我们通过这些文件指定要在网页上显示的数据库元数据。客户端可以从数百个不同的命名元数据中选择一个。客户端可以配置 N 个插槽,但我们事先不知道特定客户端希望在表单上填写哪些元数据。因为如果在渲染表单时我们需要提前知道我们需要为这个客户端模板传递哪些变量名。

我们曾想过拥有一个包含所有可能值的一致字典并每次都传递它,但这是行不通的,因为新的可用字段经常添加到客户端可以选择的可用元数据的底层池中。

正因为如此,我们曾希望使用 Mako 来模板化配置文件,但我不知道如何确定模板中的字段值,以便我可以构建一个完整的上下文传递给模板。

最佳答案

不幸的是,没有简单的方法可以从模板对象中获取变量的名称。

幸运的是,有 mako.codegen._Identifiers 类,其对象的唯一目的是在编译过程中跟踪变量。

不幸的是,它深埋在 Mako API 表面之下,编译完成后它就消失了。

幸运的是,您无需设置 Mako 在编译模板时设置的所有内容即可获得它。您所需要的只是解析树,您可以使用mako.lexer.Lexer 获得它。

这里是代码:

from mako import lexer, codegen


lexer = lexer.Lexer("${foo}", '')
node = lexer.parse()
# ^ The node is the root element for the parse tree.
# The tree contains all the data from a template
# needed for the code generation process

# Dummy compiler. _Identifiers class requires one
# but only interested in the reserved_names field
compiler = lambda: None
compiler.reserved_names = set()

identifiers = codegen._Identifiers(compiler, node)
# All template variables can be found found using this
# object but you are probably interested in the
# undeclared variables:
# >>> print identifiers.undeclared
# set(['foo'])

关于python - Mako 模板变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23574087/

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