Pular para o conteúdo

Variáveis e expressões ​

Tradução automática

Esta página foi traduzida automaticamente do inglês e ainda não foi revisada por um falante nativo; correções são bem-vindas no GitHub. Se algo não bater, vale o original em inglês. O código e os resultados são os mesmos do original, importados dos arquivos testados.

Tarefa: guardar valores em variáveis e calcular com eles.

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

q:set guarda um valor com um nome. As chaves calculam com ele: num atributo q: e no HTML. type="number" transforma texto em número, e um valor que é uma única expressão mantém o seu tipo, então total é um número. operation="increment" muda uma variável no lugar, e a página roda de cima para baixo: total foi calculado antes de quantity crescer. O default é guardado quando o valor está vazio ou falta, como o ?note= numa visita simples.

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

Veja SET-1, SET-3 e SET-5.

Licença MIT · Feito com VitePress