【问题标题】:django automatically pass context to specific templates onlydjango 仅自动将上下文传递给特定模板
【发布时间】:2012-11-19 20:40:20
【问题描述】:

我在字典中有上下文:

### settings.py. ###
CONTEXT = {'a':'b'}

还有两个使用该上下文的模板 t1.html 和 t2.html:

### t1.html ###
{{ a }}

### t2.html ###
{{ a }}

两者都应包含在许多其他模板中,例如:

### includer.html ###
{{ include 't1.html' }}

如何将 CONTEXT 仅传递给 t1.html 和 t2.html:

  1. 不会污染任何其他模板中的上下文,包括 includer.html 模板
  2. 自动,也就是说,每当使用 t1.html 和 t2.html 模板时,我不必手动将 settings.CONTEXT 附加到视图的上下文中,如下所示:

    ### views.py ###
    import settings
    from django.shortcuts import render
    
    def view1(request):
        return render(
            request,
            'includer.html',
            dict( {'c':'d'}.items() + settings.CONTEXT.items())
        )
    

可能的解决方案:

  • 一些包含语句,我可以直接在模板中编写以包含上下文?
  • 一种让上下文处理器执行此操作的方法?

【问题讨论】:

标签: django django-templates django-context


【解决方案1】:

这样做是不好itea,因为它隐藏了一些模板依赖项。

但是使用CBV,您可以创建基视图类并在使用 t1.html 和 t2.html 时从他继承。它不是自动的,但它隐含了额外的上下文。

如果没有 CBV,您应该像现在一样将 settings.CONTEXT 隐式附加到当前上下文。

【讨论】:

    【解决方案2】:

    听起来您想使用inclusion tag,您可以在标签中设置或导入所需的上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多