Skip to content

Conditionals ​

Task: show one thing or another depending on a value.

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

The first branch whose condition holds runs; q:else runs when none does. A condition is an expression, with and, or and not. Inside an attribute, < is written &lt;: a .q file is 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

See IF-1 and IF-2.

MIT Licensed · Built with VitePress