我想在php中编写一个类似var_dump()的方法来打印出所有变量以供调试。
如何从我的方法中访问所有模板变量?
{{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'})
也许有更好的办法,但我解决了。
{{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)