【问题标题】:Mako Template Variable NamesMako 模板变量名
【发布时间】:2014-06-27 18:04:12
【问题描述】:

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

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

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

用例:

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

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

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

【问题讨论】:

  • 嘿。我的回答对你有帮助吗?

标签: python templates mako


【解决方案1】:

追逐 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,makovar 是有序的,var 是唯一的,但不是有序的。

【讨论】:

    【解决方案2】:

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

    幸运的是,有 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'])
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 1970-01-01
      • 2023-03-16
      • 2011-05-08
      • 2011-12-26
      • 2013-04-16
      • 2012-05-28
      • 2013-05-14
      • 1970-01-01
      相关资源
      最近更新 更多