如何在模板中打印上下文内容?

Kug*_*gel 4 python django

如何从模板代码中打印或迭代上下文中可用的所有变量?

我知道{% debug %}但它包含太多信息.我只想打印当前上下文中可用的变量名称.

有没有办法在不编写自定义标签的情况下执行此操作?

Dan*_*man 9

使用Django调试工具栏 - 在模板选项卡上提供此功能,以及其他一些有用的调试信息.

  • 这样做的任何方式_without_修改应用程序范围的配置? (7认同)

evi*_*nan 5

如果您使用基于类的视图,您可以将当前上下文像变量一样提供给上下文:

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}}