函数
机器翻译
本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。
任务: 把一个计算写一次,在页面需要的任何地方使用。
yaml
# Recipe: a q:function, called from attributes and from the HTML.
paths:
components: ./componentsq:function 像动作一样接收 q:param:每次调用时,每个参数都会被转换成它的类型, 并按它的规则检查;default 补上省略的参数。returnType 检查返回的值。 函数可以在页面的任何表达式中调用,包括在另一个调用里面。
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