Chuyển đến nội dung

Bài 14 · Components and Helpers

Component Patterns: Yield, Blocks and Attributes

Learn the reusable-component toolkit in Ember - yield, block params, named blocks, splattributes, contextual components and the hash helper - with runnable stand-ins.

Basic components take arguments and render markup. Reusable components, the kind you put in a design system or share between teams, need more flexibility: the caller must be able to supply content, add classes and attributes, and sometimes receive data back from the component. Ember has four tools for this: {{yield}}, named blocks, ...attributes and contextual components.

Real versus stand-in. Template code is real Ember, read-only here. The runnable blocks reproduce the mechanics (a component that calls a "block" function with data) in plain JavaScript.

Yield: letting the caller provide content

A component marks where caller content goes with {{yield}}:

JavaScript
// app/components/card.gjs
<template>
  <section class="card">
    {{yield}}
  </section>
</template>
JavaScript
import Card from 'my-app/components/card';

<template>
  <Card>
    <h2>Hello</h2>
    <p>Anything can go here.</p>
  </Card>
</template>

Whatever sits between <Card> and </Card> is the block. This is the same idea as children in other frameworks, or a slot.

Block params: data back to the caller

{{yield}} can pass values to the block. The caller names them with as |x|:

JavaScript
// app/components/async-list.gjs
<template>
  {{#if @items.length}}
    <ul>
      {{#each @items as |item index|}}
        <li>{{yield item index}}</li>
      {{/each}}
    </ul>
  {{else}}
    <p>Nothing to show.</p>
  {{/if}}
</template>
JavaScript
<template>
  <AsyncList @items={{@users}} as |user index|>
    {{index}}. <strong>{{user.name}}</strong>
  </AsyncList>
</template>

The component owns the loop and the empty state; the caller decides how one item looks. This is the render prop pattern, and it is everywhere in Ember: <form> helpers, tables, dropdowns.

JS A component that yields to a block

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Named blocks

When a component has several places for content, give them names with <:name> and yield to them with {{yield to="name"}}:

JavaScript
// app/components/panel.gjs
<template>
  <div class="panel">
    <header>{{yield to="title"}}</header>
    <div class="body">{{yield}}</div>
    {{#if (has-block "footer")}}
      <footer>{{yield to="footer"}}</footer>
    {{/if}}
  </div>
</template>
JavaScript
<template>
  <Panel>
    <:title>Account</:title>
    <:default>You are signed in.</:default>
    <:footer><button type="button">Sign out</button></:footer>
  </Panel>
</template>

<:default> is the unnamed block. When you use any named block you must write the default one with its tag too. has-block (a keyword in the template tag format, global in older apps) checks whether the caller supplied a given block, so optional regions disappear when unused.

Splattributes: forwarding HTML attributes

Callers will want to add class, id, aria-*, data-test-* and event modifiers to your component. Mark the element that should receive them with ...attributes:

JavaScript
// app/components/button.gjs
<template>
  <button type="button" class="btn" ...attributes>
    {{yield}}
  </button>
</template>
JavaScript
<template>
  <Button class="btn-primary" aria-label="Save" {{on "click" this.save}}>
    Save
  </Button>
</template>

The rendered button has the classes btn btn-primary: Ember merges class, and caller attributes override the component's own for everything else (so place ...attributes after attributes that may be overridden, and before ones that must win). Modifiers like {{on}} also pass through. This is why design-system components almost always include ...attributes on the root element.

A component can have only one meaningful root for ...attributes; if there are several, pick the main element. A component with no ...attributes silently ignores attributes passed to it.

JS Stand-in: merging attributes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Contextual components and hash

Sometimes a component should hand the caller its own parts, already wired together, so the caller composes the layout. You yield a hash of components with some arguments pre-filled:

JavaScript
// app/components/tabs.gjs
import { hash } from '@ember/helper';
import TabList from './tabs/list';
import TabPanel from './tabs/panel';

export default class Tabs extends Component {
  @tracked active = this.args.initial;

  select = (id) => (this.active = id);

  <template>
    {{yield (hash
      List=(component TabList active=this.active onSelect=this.select)
      Panel=(component TabPanel active=this.active)
    )}}
  </template>
}
JavaScript
<template>
  <Tabs @initial="one" as |tabs|>
    <tabs.List />
    <tabs.Panel @id="one">First</tabs.Panel>
    <tabs.Panel @id="two">Second</tabs.Panel>
  </Tabs>
</template>

(component Name key=value) curries a component: it returns a new component with the given arguments already set. The Tabs parent keeps the state; the yielded parts share it without the caller wiring anything. This is how headless UI libraries are built.

In the stand-in below, the "parts" are functions closing over shared state:

JS Stand-in: yielding a hash of parts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Choosing a pattern

Need Use
Caller supplies content {{yield}}
Caller needs data back (per item) block params {{yield item}}
Several content regions named blocks
Caller adds class, id, ARIA, listeners ...attributes
Compose sub-parts with shared state contextual components with hash

Common mistakes

  • Omitting ...attributes. Callers then cannot add classes or test selectors.
  • Mixing {{yield}} content and named blocks without <:default>.
  • Yielding huge objects. Yield only what the block needs; it keeps the contract clear.
  • Putting layout logic in the caller. If every caller repeats the same wrapper markup, move it into the component.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does {{yield item}} do in a component's template?

    The caller names the value with as |item|, so the component supplies data and the caller supplies markup.
  2. 2. Which line lets a caller add class="wide" and data-test-id to your component's root element?

    Splattributes forward caller attributes and modifiers to the element where you write ...attributes.
  3. 3. How do you write the unnamed content when a component also uses named blocks?

    Once you use named blocks, the default block must be written explicitly as <:default>.
  4. 4. What does (component Foo a=1) return?

    It curries the component, which is how a parent yields ready-to-use child parts.

Summary

  • {{yield}} lets callers supply content; block params send data back to the block.
  • Named blocks (<:title>) provide several slots, and has-block checks if one was given.
  • ...attributes forwards class, ARIA, data attributes and modifiers to a chosen element.
  • (component ...) plus hash yields pre-wired parts for composition.
  • Pick the lightest pattern that solves the problem.

Next: Forms and Inputs

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.