Pular para o conteúdo

Funçõ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: escrever um cálculo uma vez e usá-lo onde a página precisar.

yaml
# Recipe: a q:function, called from attributes and from the HTML.
paths:
  components: ./components

Uma q:function recebe q:param como uma ação: cada argumento é convertido para o seu tipo e verificado contra as suas regras a cada chamada, e default preenche um que ficou de fora. returnType verifica o que volta. Uma função pode ser chamada em qualquer expressão da página, inclusive dentro de outra chamada.

xml
<q:component name="Prices">
  <!-- Arguments are checked against the q:params on every call. -->
  <q:function name="withTax" returnType="number">
    <q:param name="amount" type="number" required="true" min="0" />
    <q:param name="rate" type="number" default="0.1" />
    <q:return value="{round(amount * (1 + rate), 2)}" />
  </q:function>

  <q:function name="label">
    <q:param name="amount" type="number" required="true" />
    <q:return value="{'free' if amount == 0 else '$' + str(amount)}" />
  </q:function>

  <q:set name="book" value="{withTax(20)}" />

  <html>
  <body>
    <p>Book: {label(book)}</p>
    <p>Food: {label(withTax(10, 0.05))}</p>
    <p>Sample: {label(withTax(0))}</p>
  </body>
  </html>
</q:component>
xml
<q:test name="a function called from q:set and from the HTML" page="/">
  <test:visit />
  <test:expect var="book" value="22.0" />
  <test:expect text="Book: $22.0" />
</q:test>

<q:test name="an argument by position replaces the default" page="/">
  <test:visit />
  <test:expect text="Food: $10.5" />
</q:test>

<q:test name="functions compose" page="/">
  <test:visit />
  <test:expect text="Sample: free" />
</q:test>
text
tests/prices.test.q
  PASS  a function called from q:set and from the HTML
  PASS  an argument by position replaces the default
  PASS  functions compose
3 passed, 0 failed

Veja FN-1, FN-3 e FN-4.

Licença MIT · Feito com VitePress