VladVons
VladVons

Reputation: 47

How to debug all variables inside a jinja templates?

I want to write a methot like var_dump() in php to print out all variables for debug purpuse.
How to access all template variables from inside my method ?
{{ Dump() }}

def Dump() -> str:
    Res = []
    Vars = some_jinja_getall_variables() # ???
    for var in Vars:
        print(var)
        Res.append(str(var))
    return '<br>\n'.join(Res)

Tpl = Env.get_template(Route, globals = {'Dump': Dump})
Tpl.render({'var1': 'hello', 'var2': 'world'})

Upvotes: 1

Views: 582

Answers (1)

VladVons
VladVons

Reputation: 47

Perhapse there is a better way, but I solved so.
{{ Dump(self) }}

def Dump(self, aVal: bool = True) -> str:
    Res = []
    #pylint: disable-next=protected-access
    Vars = self._TemplateReference__context.parent
    for Key, Val in Vars.items():
        if (isinstance(Val, (str, int, float, dict, list))):
            Data = f'{Key} = {Val}' if aVal else f'{Key} = {type(Val).__name__}'
            print(Data)
            Res.append(Data)
    return '<br>\n'.join(Res)

Upvotes: 0

Related Questions