Read the query string
Task: filter and sort a list from values in the address.
yaml
# Recipe: read ?q= and ?sort= from the address, with defaults.
paths:
components: ./componentsquery.q is the value of ?q= in the address, and is empty when the address has none, so default gives it a value. A GET form fills the address for you. urlencode() makes a typed value safe inside a link.
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