分页列表
机器翻译
本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。
任务: 每页十条地显示 23 篇文章,并带有指向其他页的链接。
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.dbsql
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" 让查询只返回一页——URL 中 ?page= 指定的页,或者第一页——并在 posts_result.pagination 中填入总数。<ui:pager for="posts"> 画出上一页、页码和下一页, 并保留 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>不是正数的 page 就是第 1 页,从不报错:
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