跳到正文

条件 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 根据一个值显示这样或那样的内容。

yaml
# Recipe: q:if, q:elseif and q:else.
paths:
  components: ./components

第一个条件成立的分支会运行;都不成立时运行 q:else。 条件是一个表达式,可以用 and、or 和 not。在属性里,< 要写成 &lt;: .q 文件是 XML。

xml
<q:component name="Stock">
  <!-- /?stock=3 -->
  <q:set name="stock" type="number" value="{query.stock}" default="0" />

  <html>
  <body>
    <q:if condition="stock == 0">
      <p class="out">Out of stock.</p>
    </q:if>
    <q:elseif condition="stock &lt; 5">
      <p class="low">Only {stock} left.</p>
    </q:elseif>
    <q:else>
      <p>In stock.</p>
    </q:else>

    <!-- A condition is an expression: and, or, not work as in Python. -->
    <q:if condition="stock > 0 and stock % 2 == 0">
      <p>Sold in pairs: {stock // 2} pairs.</p>
    </q:if>
  </body>
  </html>
</q:component>
xml
<q:test name="no stock" page="/">
  <test:visit />
  <test:expect text="Out of stock." />
  <test:expect no-text="In stock." />
</q:test>

<q:test name="a little stock" page="/?stock=3">
  <test:visit />
  <test:expect text="Only 3 left." />
  <test:expect no-text="pairs" />
</q:test>

<q:test name="plenty, and an even number" page="/?stock=8">
  <test:visit />
  <test:expect text="In stock." />
  <test:expect text="Sold in pairs: 4 pairs." />
</q:test>
text
tests/stock.test.q
  PASS  no stock
  PASS  a little stock
  PASS  plenty, and an even number
3 passed, 0 failed

参见 IF-1 和 IF-2。

MIT 许可证 · 使用 VitePress 构建