【问题标题】:Django Templates: Add something below a variableDjango模板:在变量下面添加一些东西
【发布时间】:2018-04-26 10:58:27
【问题描述】:

我有这个 html django 模板:

{{ header }}

{{ content }}

{{ footer }}

这意味着上下文采用以下变量:页眉、内容、页脚。

有没有可能是这样的:

Template(...).render(
    dict(header='foo', content='bar', footer='blu', 
        content__post='this should be between content and footer')

需要的结果:

foo
bar
this should be between content and footer
blu

我不想修改所有模板以包含content__post,因为模板很多。

如何“注入”sn-ps post/pre(下方/上方)其他变量的位置?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    只需将中间内容添加到content 即可。如果您希望它完全自动化,这可以使用上下文处理器来完成。

    def add_something(context):
        if somecondition_maybe:
            context['content'] += "some more content to be added"
        return context
    

    然后将your_app.context_processors.add_something 添加到您的模板上下文处理器中(在settings.py 中)。

    查看更多:own context processorscontext_processors

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 1970-01-01
      • 2018-12-14
      • 2012-10-15
      • 1970-01-01
      • 2013-10-20
      • 2012-08-11
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多