【问题标题】:Django mptt, extends "base.html"Django mptt,扩展“base.html”
【发布时间】:2012-09-27 23:04:07
【问题描述】:

在base.html中:

<div id="menu_shop">
            <input name="search" placeholder="search">
            <p>Category:</p>
             {% load mptt_tags %}
<ul class="root">
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>
</div>

在视图中:

def show_category_tree(request):
    return render_to_response("base.html",
                              {'nodes': Category.tree.all()},
                              context_instance=RequestContext(request))

urls.py:

url(r'^category/', 'item.views.show_category_tree'),
url(r'^category/(?P<slug>[\w\-_]+)/$', 'item.views.by_category'),

如何在“by_category.html”中显示这个

如果我尝试(例如):

{% extends "base.html" %}


{% block content %}
{% for e in entries %}
<p><b>{{ e.name}}</b></p>

<p>{{ e.desc}}</p>
{% endfor %}

{% endblock %}

我有这个错误:

http://dpaste.com/810809/

{% extends "base.html" %} 不起作用。如果我删除它,一切正常。

【问题讨论】:

    标签: django django-mptt


    【解决方案1】:

    您看到此错误是因为by_category 的模板上下文不包括nodes

    extends 标签与模板相关,与视图无关。它使您的by_category.html 模板扩展了base.html 模板,但它不包括来自任何其他视图的模板上下文。

    最简单的解决方法是将nodes 添加到by_category 视图中的模板上下文中。

    def by_category(request, slug):
        entries = Entry.objects.filter(...)
        return render_to_response("base.html",
            {'entries': entries,
             'nodes': Category.tree.all()},
            context_instance=RequestContext(request))
    

    如果您想在许多其他视图中显示节点,这将是重复的。如果您想在所有视图中包含节点,您可能需要编写一个请求上下文处理器。如果您想将它包含在某些但不是所有页面中,请尝试编写自定义模板标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2018-06-06
      相关资源
      最近更新 更多