如何使用DRY渲染一个活动项目的菜单? [英] How to render menu with one active item with DRY?

查看:71
本文介绍了如何使用DRY渲染一个活动项目的菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想渲染如下结构:

<a href='/home'>Home</a>
<span class='active'>Community</span>
<a href='/about'>About</a>

在其中选择 Community 的菜单项。我有几个模板具有相同选项的菜单,但我不想为每个模板创建组合:

Where Community is selected menu item. I have menu with same options for several templates but I would not like to create combinations for each template:

<!-- for Home template-->
        <span class='active'>Home</span>
        <a href='/comminuty'>Community</a>
        <a href='/about'>About</a>
    ...
<!-- for Community template-->
        <a href='/home'>Home</a>
        <span class='active'>Community</span>
        <a href='/about'>About</a>
    ...
<!-- for About template-->
        <a href='/home'>Home</a>
        <a href='/community'>Community</a>
        <span class='active'>About</span>

我们有菜单项的永久列表,因此,它可能是更有效的方法-仅创建一个菜单的通用结构,然后呈现带有模板所需选项的菜单。

We have permanent list of menu items, so, it can be more effective way - to create only one generalized structure of menu then render menu with required option for template.

例如,它可以是允许这样做的标签。

For example it could be a tag that allows to do that.

推荐答案

我找到了简单而优雅的DRY解决方案。

I found easy and elegant DRY solution.

这是代码段:
http://djangosnippets.org/snippets/2421/

**Placed in templates/includes/tabs.html**

<ul class="tab-menu">
    <li class="{% if active_tab == 'tab1' %} active{% endif %}"><a href="#">Tab 1</a></li>
    <li class="{% if active_tab == 'tab2' %} active{% endif %}"><a href="#">Tab 2</a></li>
    <li class="{% if active_tab == 'tab3' %} active{% endif %}"><a href="#">Tab 3</a></li>
</ul>

**Placed in your page template**

{% include "includes/tabs.html" with active_tab='tab1' %}

这篇关于如何使用DRY渲染一个活动项目的菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆