Skip to content

Variables and expressions ​

Task: keep values in variables and compute with them.

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

q:set stores a value under a name. Braces compute with it: in a q: attribute and in the HTML. type="number" makes text a number, and a value that is a single expression keeps its type, so total is a number. operation="increment" changes a variable in place, and the page runs top to bottom: total was computed before quantity grew. default is stored when the value is empty or missing, as ?note= is on a plain visit.

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

See SET-1, SET-3 and SET-5.

MIT Licensed · Built with VitePress