Django mptt,扩展“base.html”

2024-02-11

在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/ http://dpaste.com/810809/

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


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

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

最简单的修复方法是添加nodes到您的模板上下文中by_category view.

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))

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django mptt,扩展“base.html” 的相关文章

随机推荐