Ler a query string
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: filtrar e ordenar uma lista a partir de valores no endereço.
yaml
# Recipe: read ?q= and ?sort= from the address, with defaults.
paths:
components: ./componentsquery.q é o valor de ?q= no endereço, e fica vazio quando o endereço não tem nenhum, então o default lhe dá um valor. Um formulário GET preenche o endereço para você. urlencode() deixa um valor digitado seguro dentro de um 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