Ir al contenido

Leer la query string ​

Traducción automática

Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.

Tarea: filtrar y ordenar una lista a partir de valores en la dirección.

yaml
# Recipe: read ?q= and ?sort= from the address, with defaults.
paths:
  components: ./components

query.q es el valor de ?q= en la dirección, y está vacío cuando la dirección no lo tiene, así que default le da un valor. Un formulario GET completa la dirección por ti. urlencode() hace que un valor escrito sea seguro dentro de un enlace.

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)}&amp;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 &quot;&quot;, 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&amp;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

Ver SET-1 y EXPR-12.

Licencia MIT · Hecho con VitePress