[Python] Get variables from Jinja2 template

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I need to extract variable names (with JSON) from this Jinja2 template with functions:

    {{ variable }}
    {{ some.variable.type.json }}
    {{ _("Hello") }}
    <p>Some HTML file</p>


    I need to get output something like this:

    {'some': {'variable': {'type': {'json': <scalar>}}}, 'variable': <scalar>}


    Or this:

    ["some.variable.type.json", "variable"]


    I tried Environment from jinja2:

    from jinja2 import Environment, FileSystemLoader, meta

    env = Environment(loader=FileSystemLoader(""))
    template_source = env.loader.get_source(env, "test.html")[0]
    parsed_content = env.parse(template_source)
    variables = meta.find_undeclared_variables(parsed_content)
    print(variables)


    But it returns function names in output and don't return all JSON name:

    {'some', 'variable'}


    I tried jinja2schema too:

    import jinja2schema

    with open("test.html", mode="r") as f:
    template = str("".join(f.readlines()))
    variables = jinja2schema.infer(template)

    print(variables)


    It returns what I want without functions, but when in HTML is some Jinja2 function, then I got Exception:

    jinja2schema.exceptions.InvalidExpression: line 3: "_" call is not supported


    Is there any way to get full variables from Jinja2 template withou function names? Thanks for help

    Continue reading...

Compartilhe esta Página