Django mptt,扩展了"base.html" [英] Django mptt, extends "base.html"
问题描述
在base.html中:
In 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"中显示此内容
How to display this in "by_category.html"
如果我尝试(例如):
{% extends "base.html" %}
{% block content %}
{% for e in entries %}
<p><b>{{ e.name}}</b></p>
<p>{{ e.desc}}</p>
{% endfor %}
{% endblock %}
我有此错误:
{%扩展了"base.html"%},该键不起作用.如果我删除它,一切正常.
{% extends "base.html" %} does not work. If I remove it, everything works.
推荐答案
您看到此错误,因为 by_category
的模板上下文不包含 nodes
.
You are seeing this error because your template context for the by_category
does not include nodes
.
extends
标记与模板相关,与视图无关.它使您的 by_category.html
模板扩展了 base.html
模板,但不包括任何其他视图中的模板上下文.
The extends
tag is related to the template, not the view. It makes your by_category.html
template extend the base.html
template, but it does not include the template context from any other view.
最简单的解决方法是在 by_category
视图中将 nodes
添加到模板上下文中.
The easiest fix would be to add nodes
to your template context in the 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))
如果要在许多其他视图中显示节点,则将是重复的.如果要在所有视图中包括节点,则可能需要编写请求上下文处理器.如果您想将其包括在某些而非全部页面中,请尝试编写自定义模板标记.
This would be repetitive if you want to display the nodes in lots of other views. If you want to include the nodes in all views, you may want to write a request context processor. If you want to include it in some but not all pages, then try writing a custom template tag.
这篇关于Django mptt,扩展了"base.html"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!