读取查询字符串
机器翻译
本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。
任务: 根据地址中的值筛选和排序一个列表。
yaml
# Recipe: read ?q= and ?sort= from the address, with defaults.
paths:
components: ./componentsquery.q 是地址中 ?q= 的值;地址中没有它时为空,所以用 default 给它一个值。 GET 表单会替你填好地址。urlencode() 让输入的值可以安全地放进链接里。
xml
<q:component name="Search">
<!-- query.<name> is the address's ?name=; a missing one is empty. -->
<q:set name="q" value="{query.q}" default="" />
<q:set name="order" value="{query.order}" default="az" />
<q:set name="words" type="array" value='["pear", "apple", "plum", "peach", "fig"]' />
<q:set name="words" value="{sort(words, order == 'za')}" />
<html>
<body>
<form method="GET">
<input name="q" value="{q}" />
<button>Search</button>
</form>
<p>Results for "{q}", sorted {order}:</p>
<ul>
<q:loop type="array" var="w" items="{words}">
<q:if condition="contains(w, lower(q))">
<li>{w}</li>
</q:if>
</q:loop>
</ul>
<!-- urlencode keeps a typed value safe inside a link. -->
<a href="/?q={urlencode(q)}&order=za">Z to A</a>
</body>
</html>
</q:component>xml
<q:test name="no ?q= shows everything, sorted by the default" page="/">
<test:visit />
<test:expect text="Results for "", sorted az: apple fig peach pear plum" />
<test:expect var="order" value="az" />
</q:test>
<q:test name="?q= filters" page="/?q=PE">
<test:visit />
<test:expect text="peach pear" />
<test:expect no-text="plum" />
</q:test>
<q:test name="two parameters at once" page="/?q=p&order=za">
<test:visit />
<test:expect text="plum pear peach apple" />
</q:test>text
tests/search.test.q
PASS no ?q= shows everything, sorted by the default
PASS ?q= filters
PASS two parameters at once
3 passed, 0 failed