lyc*_*ian 6 python templates mako
是否可以在渲染之前获取Mako模板中的变量名称?
from mako.template import Template
bar = Template("${foo}")
# something like:
# >> print bar.fields()
# ['foo']
Run Code Online (Sandbox Code Playgroud)
使用案例:
我们有配置文件,我们指定数据库中的元数据以显示在网页上.客户端可以选择几百个不同的命名元数据中的一个.客户端可以配置N个插槽,但我们事先并不知道特定客户端希望在表单上填写哪些元数据.因为如果在渲染表单时我们需要提前知道我们需要为此客户端模板传递哪些变量名称.
我们曾想过拥有一个包含所有可能值的一致字典并在每次传递它但由于新的可用字段经常添加到客户端可以选择的基础可用元数据池中而无法工作.
因此,我们希望使用Mako来模拟配置文件,但我无法弄清楚如何使用模板中的字段值来确定是否可以构建一个完整形式的Context以传递给模板.
不幸的是,没有简单的方法可以从模板对象中获取变量的名称。
幸运的是,有一个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'])
Run Code Online (Sandbox Code Playgroud)