【问题标题】:Passing arguments into partials automatically自动将参数传递给部分
【发布时间】:2016-03-02 11:09:52
【问题描述】:

问题是header.html 部分总是包含保存在数据库中的类别字典。包括这个带参数的部分

{% include "_partials/header.html" with categories %}

每次渲染局部时我都需要传递类别字典

render("index.html", {"flowers":flowers, "categories":categories}) 
render("details.html", {"flower":flower, "categories":categories})
...

有什么解决方案,header.html partials 总是包含categories 字典。

【问题讨论】:

标签: django django-templates


【解决方案1】:

使用包含标签解决了它。

templatetags/tags.py 文件中创建自定义标签

from django import template
from flowers.models import Category
register = template.Library()
@register.inclusion_tag('_partials/nav.html')
def show_categories():
    categories = Category.objects.all()
    print categories
    return {'categories':categories}

_partials/nav.html 文件中为其创建模板

<nav>
   <ul>
        {% for category in categories %}
            <li><a href="{% url 'category:detail' category.id' %}">{{ category.name }}</a></li>
        {% endfor %}
   </ul>
</nav>

最后,使用了那个标签

{% load tags %}
{% show_categories %}

【讨论】:

    【解决方案2】:

    您应该为此使用custom inclusion tag

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多