2015-02-10 77 views
1

我正試圖找到在Jinga2模板中使用無序列表生成嵌套菜單的最佳方法。到目前爲止,它工作正常,但我無法找到設置活動鏈接的好方法,因爲父項和子項需要屬於活動類才能工作。Jinja2模板中嵌套菜單的最佳做法

這是我的導航對象。

navigation = [ 
    {'href': '/', 'id': 'dashboard', 'caption': 'Dashboard', 'icon-class': 'fa fa-dashboard'}, 
    {'href': '/electricity', 'id': 'electricity', 'caption': 'Electricity', 'icon-class': 'fa fa-cogs', 
     'sub-item': (
      {'href': '/electricity?usage', 'id': 'electricity-usage', 'caption': 'Usage'}, 
      {'href': '/electricity?status', 'id': 'electricity-status', 'caption': 'Status'}, 
     )} 
] 

CherryPy的根類:

class Root: 
@cherrypy.expose 
def index(self): 
    tmpl = env.get_template('base.html') 
    return tmpl.render(siteName='Test', navigation_bar=navigation, title='Index') 

@cherrypy.expose 
def electricity(self): 
    tmpl = env.get_template('base.html') 
    return tmpl.render(siteName='Test', navigation_bar=navigation, active_page='electricity', title='Electricity') 

這與代碼菜單中的部分我目前Jinja2的模板文件:

{% set active_page = active_page|default('dashboard') -%} 

    <aside> 
     <div id="sidebar" class="nav-collapse "> 
      <!-- sidebar menu start--> 

      <ul class="sidebar-menu" id="nav-accordion"> 
       {% for pitem in navigation_bar %} 
       <li class="mt"> 
        <a {% if id == active_page %} class="active"{% endif %} href="{{ pitem['href']|e }}"> 
         <i class="{{ pitem['icon-class']|e }}"></i> 
         <span>{{ pitem['caption']|e }}</span> 
        </a> 
        {% if pitem['sub-item'] %} <ul class="sub"> {% endif %} 
        {% for sitem in pitem['sub-item'] %} 
         <li {% if id == active_page %} class="active"{% endif %} ><a href="{{ sitem['href'] }}">{{ sitem['caption'] }}</a></li> 
        {% endfor %} 
        {% if pitem['sub-item'] %} </ul> {% endif %} 
       </li> 
       {% endfor %} 
      </ul> 

      <!-- sidebar menu end--> 
     </div> 
    </aside> 

這是它所需要的結構的例子生成:

<ul class="sidebar-menu" id="nav-accordion">   
<li class="mt"> 
    <a href="index.html"> 
     <i class="fa fa-dashboard"></i> 
     <span>Dashboard</span> 
    </a> 
</li> 

<li class="sub-menu"> 
    <a class="active" href="javascript:;" > 
     <i class="fa fa-desktop"></i> 
     <span>UI Elements</span> 
    </a> 
    <ul class="sub"> 
     <li class="active"><a href="general.html">General</a></li> 
     <li><a href="buttons.html">Buttons</a></li> 
     <li><a href="panels.html">Panels</a></li> 
    </ul> 
</li> 

請注意,父列表中的<a><li>都需要屬於「活動」類。

回答

0

您是否將導航HTML放在子模板中,而不是父基本模板?您可以將所有導航模板HTML放置在基本模板中,並在子模板中設置active_page變量,如文檔中所述:http://jinja.pocoo.org/docs/dev/tricks/#highlighting-active-menu-items

我不明白你爲什麼從cherrypy傳遞active_page變量,你可以簡單地將其設置在子模板中。

你說:

注意,無論是在父列表中的<a><li>需要是一流的「積極」的。

我不明白,有什麼使用{% if id == active_page %} class="active"{% endif %}兩次,在<a>標籤,並在<li>標籤停止嗎?

+0

謝謝Isa,我現在明白這一點。我已經在模板中完成了這個工作,它運行良好。 – Ceebs 2015-02-14 08:41:30