如何从模板代码中打印或迭代上下文中可用的所有变量?
我知道{% debug %}但它包含太多信息.我只想打印当前上下文中可用的变量名称.
有没有办法在不编写自定义标签的情况下执行此操作?
如果您使用基于类的视图,您可以将当前上下文像变量一样提供给上下文:
class MainView(TemplateView):
template_name = 'base.html'
def get_context_data(self, **kwargs):
ctx = super(MainView, self).get_context_data(**kwargs)
ctx['ctx'] = ctx
return ctx
Run Code Online (Sandbox Code Playgroud)
比你可以访问上下文 {{ctx}}