1.  背景及基本思想

Genshi 模板默认提供的 py:if 语法不支持 else ,见#else support in #if directive,官方建议使用 py:choose 来代替。这里给出带有详细解释的示例。

2.  示例1:类似 switch 的写法(根据特定变量的取值来决定分支选择)

<py:choose test="condition">
  <py:when test="'a'">condition 取值为 'a'</py:when>
  <py:when test="'b'">condition 取值为 'b'</py:when>
  <py:otherwise>condition 的取值既不是 'a' 也不是 'b'</py:otherwise>
</py:choose>

这里 py:choose 的 test 参数指定的是用于条件判断的变量。

3.  示例2:类似标准 Python 的 if-elif-else 的写法(每个分支有自己独立的判定条件)

<py:choose test="">
  <py:when test="condition_1 == 'a'">condition_1 取值为 'a'</py:when>
  <py:when test="condition_2 == 'b'">condition_2 取值为 'b'</py:when>
  <py:otherwise>condition_1 的取值不是 'a' ,而且 condition_2 的取值不是 'b'</py:otherwise>
</py:choose>

在 py:when 中使用完整逻辑表达式的要点在于 py:choose 的 test 参数要留空。

GlossyBlue theme adapted by David Gilbert
Powered by PmWiki