跳到正文

变量与表达式 ​

机器翻译

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

任务: 把值保存在变量里,并用它们计算。

yaml
# Recipe: variables with q:set, and expressions in braces.
paths:
  components: ./components

q:set 以一个名字保存一个值。花括号用它计算:在 q: 属性里和 HTML 里都可以。 type="number" 把文本变成数字,而只有一个表达式的值会保留它的类型,所以 total 是一个数字。operation="increment" 就地修改变量,页面从上到下运行:total 是在 quantity 增加之前计算的。当值为空或不存在时(例如普通访问时的 ?note=), 保存的是 default。

xml
<q:component name="Receipt">
  <q:set name="item" value="Coffee beans" />
  <q:set name="price" type="number" value="12.5" />
  <q:set name="quantity" type="number" value="3" />
  <!-- A value that is one expression keeps its type: total is a number. -->
  <q:set name="total" value="{price * quantity}" />
  <!-- default is stored when the value is empty or missing. -->
  <q:set name="note" value="{query.note}" default="no note" />
  <q:set name="quantity" operation="increment" />

  <html>
  <body>
    <h1>{upper(item)}</h1>
    <p>{quantity} bags at {price} = {total}</p>
    <p>With the extra bag: {price * quantity}</p>
    <p>Note: {note}</p>
  </body>
  </html>
</q:component>
xml
<q:test name="expressions compute with the variables" page="/">
  <test:visit />
  <test:expect text="COFFEE BEANS" />
  <test:expect text="4 bags at 12.5 = 37.5" />
  <test:expect text="With the extra bag: 50.0" />
  <test:expect var="total" value="37.5" />
</q:test>

<q:test name="the default fills an empty value" page="/">
  <test:visit />
  <test:expect text="Note: no note" />
</q:test>

<q:test name="a value from the URL replaces the default" page="/?note=gift">
  <test:visit />
  <test:expect text="Note: gift" />
</q:test>
text
tests/receipt.test.q
  PASS  expressions compute with the variables
  PASS  the default fills an empty value
  PASS  a value from the URL replaces the default
3 passed, 0 failed

参见 SET-1、SET-3 和 SET-5。

MIT 许可证 · 使用 VitePress 构建