Skip to content

Reusable components ​

Task: write a card once and use it on any page, with different content.

yaml
# Recipe: a reusable component with props and a slot, kept out of the URLs.
paths:
  components: ./components

A component is a .q file too. Its q:params are its props, and q:slot is where the caller's content goes. Keep it in a folder whose name starts with _: it can be imported, and it never answers a URL.

xml
<q:component name="Card">
  <!-- Props are q:params; the caller's content goes where q:slot is. -->
  <q:param name="title" type="string" required="true" />
  <q:param name="tone" type="string" default="plain" />

  <section class="card card-{tone}">
    <h2>{title}</h2>
    <div class="card-body">
      <q:slot />
    </div>
  </section>
</q:component>

q:import brings it into the page, and <Card> uses it. Each attribute is a prop, and the content between the tags fills the slot, computed with the page's variables:

xml
<q:component name="Dashboard">
  <!-- from="_shared": a folder whose name starts with _ is never a page. -->
  <q:import component="Card" from="_shared" />
  <q:set name="open" type="number" value="4" />

  <html>
  <body>
    <Card title="Open tickets">
      <p>{open} waiting for an answer.</p>
    </Card>
    <Card title="Warning" tone="alert">
      <p>The mail server is slow today.</p>
    </Card>
  </body>
  </html>
</q:component>
xml
<q:test name="each card has its title and the page's content" page="/">
  <test:visit />
  <test:expect text="Open tickets 4 waiting for an answer." />
  <test:expect text="Warning The mail server is slow today." />
</q:test>

<q:test name="a component in a _ folder is not a page" page="/_shared/Card">
  <test:visit />
  <test:expect status="404" />
</q:test>
text
tests/cards.test.q
  PASS  each card has its title and the page's content
  PASS  a component in a _ folder is not a page
2 passed, 0 failed

See COMP-1, COMP-3 and ROUTE-3.

MIT Licensed · Built with VitePress