从每个单独的视图将参数传递到base.html

时间:2018-07-12 11:25:23

标签: django

我在base.html中有这样一个顶部导航栏

<div class='section-topbar'>
  <div class="row">
    <nav class="col-md-12">
      <ul class="nav nav-tabs nav-justified">
        {% for sec in sections %} {% if sec == current_section %}
        <li class="active">
          <a href="/article/list/{{ current_section.id }}">{{ current_section.name }}</a>
        </li>
        {% else %}
        <li>
          <a href="/article/list/{{ sec.id }}">{{ sec.name }}</a>
        </li>
        {% endif %} {% endfor %}
        <br class="cbt">
      </ul>
    </nav>
  </div> <!--first row-->
</div>

它旨在呈现在每个页面上,并从视图中检索两个上下文参数sectionscurrent_section

context = {"page":page,
           "current_section": section,
           "sections": sections,}
return render(request, "article/article_list.html", context)

所以我必须将每个视图的额外参数传递给模板,

是否可以一次性通过并全局启用它们?

2 个答案:

答案 0 :(得分:3)

编写自己的context_processor,它将在每个视图的上下文中注入给定的变量,并且它们将在每个模板中可用。

# myproject/myapp/context_processors.py

def sections_processor(request):
    # do something ...
    # then return your variables
    return {'sections': sections, 'current_section': section}

您需要在设置文件中注册此上下文处理器,以便Django可以运行它:

# myproject/myproject/settings.py

TEMPLATES = [{
    'OPTIONS': {
        'context_processors': [
            ...
            'myappp.context_processors.sections_processor',
        ]
    }
}]

答案 1 :(得分:2)

是的,您可以使用context_processors,因此默认情况下,您的每个模板都将加载此变量...但是请记住,您的所有页面都必须能够在context_processor中运行代码

https://docs.djangoproject.com/pt-br/2.0/_modules/django/template/context_processors/

编辑:这里有一些代码,您可以尝试一下

settings.py

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',        
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [                
            ...
            'youapp.context_processors.yourcontextname_context_processor',
        ],
    },
}]

context_processors.py#在应用内创建

def yourcontextname_context_processor(request):
    ... # Your logic        
    data = {
        'something': "something",
        'another_thing': "another_thing",
        'array_of_thing': ["thing", "thing", "thing", ],
    }

    return data

在您的html中

{{ something }}
{{ another_thing }}
{% for thing in array_of_thing %}
    {{ thing }}
{% endfor %}