Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Templates and Components

Function Components, Attributes and Slots

Build reusable HEEx function components with attr, slot and render_slot: declare types and defaults, pass inner content, use named slots and global attributes.

A function component is a function that takes a map of assigns and returns a template. Components are how Phoenix pages avoid copy-paste: a button, a card, a modal or a table is written once and used anywhere with <.button> or <.card>.

In this lesson you will write components, declare their inputs with attr, accept child content with slots and accept extra HTML attributes with the :global type. You need the HEEx basics first.

The Phoenix code is read-only. TryIts imitate components with JavaScript functions that return HTML strings.

A first component

ELIXIR
defmodule BlogWeb.Components do
  use Phoenix.Component

  attr :name, :string, required: true

  def greeting(assigns) do
    ~H"""
    <p class="greeting">Hello, {@name}!</p>
    """
  end
end

Call it from any template by importing the module and using a dot before the name:

HEEX
<.greeting name="Ada" />
<.greeting name={@user.name} />

A string attribute may use quotes; any other expression needs braces. A component returns a rendered template (~H), and the function must take exactly one argument named assigns.

Declaring attributes

attr documents and validates inputs at compile time:

ELIXIR
attr :label, :string, required: true
attr :variant, :string, default: "primary", values: ["primary", "danger", "ghost"]
attr :disabled, :boolean, default: false
attr :count, :integer, default: nil
attr :items, :list, default: []
attr :user, :map, default: nil

def badge(assigns) do
  ~H"""
  <span class={["badge", "badge-#{@variant}", @disabled && "opacity-50"]}>
    {@label}
  </span>
  """
end

Common types are :string, :integer, :float, :boolean, :atom, :list, :map, :any, :global and a struct module such as Blog.Post. Wrong usage produces a compile-time warning: a missing required attribute, an unknown attribute or a value not in values. Defaults are applied before the function runs, so @variant is always set.

Global attributes

Components that wrap a native element should let callers add id, class, data-* and aria-* attributes without declaring each one. The :global type collects them:

ELIXIR
attr :class, :string, default: nil
attr :rest, :global, include: ~w(href download)

def card(assigns) do
  ~H"""
  <div class={["card", @class]} {@rest}>
    {render_slot(@inner_block)}
  </div>
  """
end

<.card id="intro" data-test="card" class="mt-4">...</.card> passes id and data-test to the <div> through {@rest}. Standard global HTML attributes are accepted automatically; include: adds extra ones.

Slots

A slot is content the caller provides. The default slot is called inner_block and is rendered with render_slot/1:

HEEX
<.card>
  <h2>Title</h2>
  <p>Anything goes here.</p>
</.card>

Named slots give structure. Declare them with slot and fill them with <:name> tags:

ELIXIR
slot :header
slot :inner_block, required: true
slot :footer

def panel(assigns) do
  ~H"""
  <section class="panel">
    <header :if={@header != []}>{render_slot(@header)}</header>
    <div>{render_slot(@inner_block)}</div>
    <footer :if={@footer != []}>{render_slot(@footer)}</footer>
  </section>
  """
end
HEEX
<.panel>
  <:header>Settings</:header>
  Change your options below.
  <:footer><button>Save</button></:footer>
</.panel>

Each named slot is a list (empty when not supplied), so test @header != [] to render optional parts.

Slots with attributes and arguments

A slot can declare its own attributes, and a slot can pass data back to the caller. This is how table components work:

ELIXIR
attr :rows, :list, required: true

slot :col, required: true do
  attr :label, :string
end

def table(assigns) do
  ~H"""
  <table>
    <thead><tr><th :for={col <- @col}>{col.label}</th></tr></thead>
    <tbody>
      <tr :for={row <- @rows}>
        <td :for={col <- @col}>{render_slot(col, row)}</td>
      </tr>
    </tbody>
  </table>
  """
end
HEEX
<.table rows={@posts}>
  <:col :let={post} label="Title">{post.title}</:col>
  <:col :let={post} label="Author">{post.author.name}</:col>
</.table>

render_slot(col, row) gives each row to the slot, and :let={post} names it on the caller side. The component controls the loop; the caller controls the cell content.

Calling components from other modules

Use the module name: <BlogWeb.Components.greeting name="x" /> for a remote call, or import BlogWeb.Components once. Generated projects import CoreComponents into every view through use BlogWeb, :html.

Components, modeled

JS A card component with default and named slots

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

No output.

A table with slot arguments, modeled

JS render_slot(col, row)

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

No output.

Each render function plays the role of render_slot(col, row): the table decides when to call it, the caller decides what it shows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a function component's single parameter be named?

    ~H reads the variable assigns, so the parameter must be called assigns.
  2. 2. Which renders the default slot's content?

    The default slot is inner_block and is rendered with render_slot/1.
  3. 3. What does attr :rest, :global do?

    The :global type gathers undeclared standard HTML attributes into one map for {@rest}.
  4. 4. How do you give each row to a slot in a table component?

    render_slot/2 passes an argument; the caller binds it with :let.

Summary

  • A function component takes assigns and returns ~H; call it as <.name ... />.
  • attr declares typed, defaulted, validated inputs; :global forwards HTML attributes.
  • slot and render_slot accept child content; named slots (<:header>) build structured components.
  • Slot arguments with :let let a component feed data back to the caller's markup.

Next: Layouts and core components