Mako template variable names

Is it possible to get variable names in a Mako template before rendering?

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

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

Use Case:

We have configuration files in which we specify metadata from the database that will be displayed on the web page. A client can select one of several hundred different pieces of named metadata. There are N slots that the client can configure, but we do not know in advance which pieces of metadata that a particular client would like to fill out on the form. Because if this is when visualizing the form, we need to know in advance what variable names we need to pass for this client template.

We thought that you have a consistent dictionary with all possible values ​​and this is transmitted at every moment of time, but it was inoperative, since new available fields are often added to the base pool of available metadata that the client could select.

Because of this, we hoped to use Mako to create template configuration files, but I cannot figure out how to determine using the field values ​​in the template so that I can create a fully formed Context to go to the template.

+4
source share
2 answers

Unfortunately, there is no easy way to get variable names from a template object.

, mako.codegen._Identifiers - .

, 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'])
+2

. , - , .

    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, , , .

0

Source: https://habr.com/ru/post/1539978/


All Articles