跳到正文

每个 URL 一个页面 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 用一个文件为每一项响应一个 URL。

yaml
# Recipe: one file answers /product/1, /product/2 and so on.
paths:
  components: ./components

文件名或文件夹名中的 [name] 路径段可以匹配任何值,页面会把它作为变量 name 得到。它以文本形式到达;在 q:set 上加 type="integer" 可以把它变成数字。

xml
<q:component name="Product">
  <!-- components/product/[id].q answers /product/7 with id = "7". -->
  <q:set name="products" type="array"
         value='[{"name": "Kettle", "price": 35}, {"name": "Teapot", "price": 22}]' />
  <q:set name="n" type="integer" value="{id}" />

  <html>
  <body>
    <q:if condition="n >= 1 and n &lt;= len(products)">
      <h1>{products[n - 1].name}</h1>
      <p>Product {id}: ${products[n - 1].price}</p>
    </q:if>
    <q:else>
      <h1>No product {id}</h1>
    </q:else>
  </body>
  </html>
</q:component>
xml
<q:test name="the URL segment becomes a variable" page="/product/2">
  <test:visit />
  <test:expect text="Teapot" />
  <test:expect text="Product 2: $22" />
  <test:expect var="id" value="2" />
</q:test>

<q:test name="one file answers every id" page="/product/1">
  <test:visit />
  <test:expect text="Kettle" />
</q:test>

<q:test name="an id with no product says so" page="/product/9">
  <test:visit />
  <test:expect text="No product 9" />
</q:test>
text
tests/product.test.q
  PASS  the URL segment becomes a variable
  PASS  one file answers every id
  PASS  an id with no product says so
3 passed, 0 failed

有数据库时,页面按这个 id 读取对应的行:参见 编辑一行。规则: ROUTE-1。

MIT 许可证 · 使用 VitePress 构建