鍍金池/ 教程/ Python/ 提示和技巧
提示和技巧
從其它的模板引擎切換
集成
沙箱
擴(kuò)展
常見(jiàn)問(wèn)題
介紹
模板設(shè)計(jì)者文檔
API

提示和技巧

這部分文檔展示了一些 Jinja2 模板的提示和技巧。

Null-Master 退回

Jinja2 支持動(dòng)態(tài)繼承并且只要沒(méi)有 extends 標(biāo)簽被訪問(wèn)過(guò),就不分辨父模板和子模 板。而這會(huì)導(dǎo)致令人驚訝的行為:首個(gè) extends 標(biāo)簽前的包括空白字符的所有東西 會(huì)被打印出來(lái)而不是被忽略,這也可以用作一個(gè)巧妙的方法。

通常,繼承一個(gè)模板的子模板來(lái)添加基本的 HTML 骨架。而把 extends 標(biāo)簽放在 if 標(biāo)簽中,當(dāng) standalone 變量值為 false 時(shí)(按照默認(rèn)未定義也為 false )繼 承布局模板是可行的。此外,一個(gè)非?;镜墓羌軙?huì)被添加到文件,這樣如果確實(shí)帶 置為 True 的 standalone 渲染,一個(gè)非?;镜?HTML 骨架會(huì)被添加:

{% if not standalone %}{% extends 'master.html' %}{% endif -%}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>{% block title %}The Page Title{% endblock %}</title>
<link rel="stylesheet" href="style.css" type="text/css">
{% block body %}
  <p>This is the page body.</p>
{% endblock %}

交替的行

如果你想要對(duì)一個(gè)表格或列表中的每行使用不同的樣式,可以使用 loop 對(duì)象的 cycle 方法:

<ul>
{% for row in rows %}
  <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
</ul>

cycle 可接受無(wú)限數(shù)目的字符串。每次遭遇這個(gè)標(biāo)簽,列表中的下一項(xiàng) 就會(huì)被渲染。

高亮活動(dòng)菜單項(xiàng)

你經(jīng)常想要一個(gè)帶有活動(dòng)導(dǎo)航項(xiàng)的導(dǎo)航欄。這相當(dāng)容易實(shí)現(xiàn)。因?yàn)樵?block 外 的聲明在子模板中是全局的,并且在布局模板求值前執(zhí)行,在子模板中定義活動(dòng)的 菜單項(xiàng):

{% extends "layout.html" %}
{% set active_page = "index" %}

布局模板之后就可以訪問(wèn) active_page 。此外,這意味著你可以為它定義默認(rèn) 值:

{% set navigation_bar = [
    ('/', 'index', 'Index'),
    ('/downloads/', 'downloads', 'Downloads'),
    ('/about/', 'about', 'About')
] -%}
{% set active_page = active_page|default('index') -%}
...
<ul id="navigation">
{% for href, id, caption in navigation_bar %}
  <li{% if id == active_page %} class="active"{% endif
  %}><a href="{{ href|e }}">{{ caption|e }}</a>/li>
{% endfor %}
</ul>
...

訪問(wèn)父級(jí)循環(huán)

特殊的 loop 變量總是指向最里層的循環(huán)。如果想要訪問(wèn)外層的循環(huán),可以給它 設(shè)置別名:

<table>
{% for row in table %}
  <tr>
  {% set rowloop = loop %}
  {% for cell in row %}
    <td id="cell-{{ rowloop.index }}-{{ loop.index }}>{{ cell }}</td>
  {% endfor %}
  </tr>
{% endfor %}
</table>
上一篇:API下一篇:沙箱