Python Mako模板变量名
在渲染之前,是否可以获取Mako模板中变量的名称Python Mako模板变量名,python,templates,mako,Python,Templates,Mako,在渲染之前,是否可以获取Mako模板中变量的名称 from mako.template import Template bar = Template("${foo}") # something like: # >> print bar.fields() # ['foo'] 用例: 我们有配置文件,通过配置文件,我们可以指定要在网页上显示的数据库元数据。客户端可以从几百个不同的命名元数据片段中选择一个。客户机可以配置N个插槽,但我们事先不知道特定客户机希望在表单上填写哪些元数据。因
from mako.template import Template
bar = Template("${foo}")
# something like:
# >> print bar.fields()
# ['foo']
用例:
我们有配置文件,通过配置文件,我们可以指定要在网页上显示的数据库元数据。客户端可以从几百个不同的命名元数据片段中选择一个。客户机可以配置N个插槽,但我们事先不知道特定客户机希望在表单上填写哪些元数据。因为如果在呈现表单时出现这种情况,我们需要提前知道需要为该客户机模板传递哪些变量名
我们曾想过要有一个包含所有可能值的一致字典,并在每次传递该字典,但这是行不通的,因为新的可用字段经常添加到客户端可以选择的可用元数据的底层池中
因此,我们希望使用Mako对配置文件进行模板化,但我不知道如何确定模板中的字段值,以便我可以构建完整格式的上下文传递到模板。不幸的是,没有简单的方法从模板对象获取变量的名称 幸运的是有
mako.codegen.\u标识符
类,其对象的唯一目的是在编译过程中跟踪变量
不幸的是,它被深埋在MakoAPI表面之下,在编译完成后就消失了
幸运的是,您可以在不设置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'])
追逐Mako变量一点也不好玩。我拼凑了这个小函数来从模板中提取变量-可以随意使用和改进
def ListMakoVariables(template):
'''
Extract Mako variables from template.
'''
start = 'XXXX${'
stop = '}YYYY'
makovars = []
splitReady = template.replace('${',start).replace('}',stop)
startParts = splitReady.split('XXXX')
for startStr in startParts:
if '}' in startStr:
makovars.append(startStr.split('YYYY')[0])
vars = set(makovars)
return vars, makovars
FWIW、makovars是有序的,VAR是唯一的,但不有序。嘿。我的回答对你有帮助吗?