我有一个使用MPTT包的django项目(相当简单),通过它我为特定模型创建了类别。 我正在创建一个基于MPTT的菜单系统,但我发现自己在我的视图中重复了我的代码,更具体:
def index(request):
menu = MyCategory.objects.all()
def viewitem(request, item_slug):
menu = MyCategory.objects.all()
这应该重构为模板标签吗?我应该做一个辅助功能吗?或者创建一个中间件上下文,将对象传递给模板?根据django逻辑,这将是最好的实现?从示例中可以看出,我只返回一个由现有标签使用的查询集:
{% if menu.exists %}
<nav id="topnavigation">
<ul>
{% spaceless %}
{% recursetree menu %}
<li>
<a href="{% url 'view-category' node.slug %}">{{ node.title }}</a>
{% if not node.is_leaf_node %}
<ul class="submenu">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
{% endspaceless %}
</ul>
</nav>
{% endif %}
答案 0 :(得分:2)
Django方法是使用基于类的视图并创建custom Mixin以包含重复的代码。所以Mixin看起来像这样:
class MenuContextMixin(object):
def get_context_data(self, **kwargs):
context = super(MenuContextMixin, self).get_context_data(**kwargs)
context['menu'] = MyCategory.objects.all()
return context
它的用法如下:
class IndexView(MenuContextMixin, TemplateView):
template_name = "index.html"
由于您使用的是基于函数的视图,我认为最好的解决方案是编写一个辅助函数来扩展您的上下文。例如。 views.py:
def get_extra_context():
return {
'menu': MyCategory.objects.all(),
}
def index(request):
...
context.update(get_extra_context())
return render_to_response('index.html', context)