Pular para o conteúdo

Uma lista paginada ​

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: mostrar 23 posts, dez de cada vez, com links para as outras páginas.

yaml
# Recipe: a long list, one page at a time, with the links to the others.
paths:
  components: ./components
  migrations: ./migrations

datasources:
  db:
    driver: sqlite
    database: ./data/blog.db
sql
CREATE TABLE posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL
);

-- 23 posts: "Post 1" … "Post 23".
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 23)
INSERT INTO posts (title) SELECT 'Post ' || i FROM n;

paginate="true" faz a consulta devolver uma página — a do ?page= da URL, ou a primeira — e preenche posts_result.pagination com os totais. <ui:pager for="posts"> desenha anterior, os números das páginas e próxima, mantendo os outros parâmetros da URL.

xml
<q:component name="Posts">
  <!-- paginate: the page is the URL's ?page= (page 1 without it). -->
  <q:query name="posts" datasource="db" paginate="true" page_size="10">
    SELECT id, title FROM posts ORDER BY id DESC
  </q:query>

  <ui:window title="Posts">
    <ui:text>
      {posts_result.pagination.startRecord}–{posts_result.pagination.endRecord}
      of {posts_result.pagination.totalRecords}
    </ui:text>
    <ui:list source="{posts}" as="p">
      <ui:item><ui:text>{p.title}</ui:text></ui:item>
    </ui:list>
    <!-- Previous, the page numbers, next — keeping the URL's other parameters. -->
    <ui:pager for="posts" />
  </ui:window>
</q:component>

Um page que não é um número positivo é a página 1, nunca um erro:

xml
<q:test name="the first page" page="/">
  <test:visit />
  <test:expect text="1–10 of 23" />
  <test:expect text="Post 23" />
  <test:expect text="Post 14" />
  <test:expect no-text="Post 13" />
</q:test>

<q:test name="the last page" page="/">
  <test:visit page="3" />
  <test:expect text="21–23 of 23" />
  <test:expect text="Post 1" />
  <test:expect no-text="Post 4" />
</q:test>

<q:test name="a page that is not a number is page 1" page="/">
  <test:visit page="abc" />
  <test:expect text="1–10 of 23" />
</q:test>
text
tests/posts.test.q
  PASS  the first page
  PASS  the last page
  PASS  a page that is not a number is page 1
3 passed, 0 failed

Veja DB-2, DB-9 e UI-11.

Licença MIT · Feito com VitePress