Chuyển đến nội dung

Bài 11 · Templates and Components

HEEx Templates: Syntax and Escaping

Learn HEEx, Phoenix's HTML-aware template language: interpolation, if and for, assigns, attributes, comments and automatic escaping that blocks XSS.

HEEx (HTML + EEx) is the template language of Phoenix. A HEEx file is HTML with small islands of Elixir code. Unlike plain string templates, HEEx understands HTML: it validates tags, escapes output by default and can track which parts of a page changed, which is what makes LiveView efficient.

This lesson covers the syntax you will use every day: interpolation, conditionals, loops, attributes and the escaping rules that keep your pages safe. You should already know how a controller renders a template.

HEEx needs Phoenix, so the template snippets are read-only. The TryIts model escaping and loops with plain JavaScript.

Where templates live

A controller PostController renders through a module BlogWeb.PostHTML. Template files sit in a folder of the same name:

ELIXIR
defmodule BlogWeb.PostHTML do
  use BlogWeb, :html

  embed_templates "post_html/*"
end

embed_templates turns each file such as post_html/index.html.heex into a function index/1. The controller call render(conn, :index, posts: posts) passes %{posts: posts} as assigns. You can also write small templates inline with the ~H sigil:

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

Interpolation

Use curly braces for values inside tags and text. Assigns are read with @name:

HEEX
<h1>{@post.title}</h1>
<p>By {@post.author.name} on {Calendar.strftime(@post.inserted_at, "%B %d, %Y")}</p>
<a href={~p"/posts/#{@post}"}>Read more</a>
<div class={["card", @featured && "card-featured"]}>...</div>

Older projects use <%= @name %> for body interpolation and <%= ... %> blocks; both work, but the curly brace form is the modern way for plain values. Attribute values are always written as attr={expression} without quotes.

  • A class list is joined for you, and false or nil entries are dropped.
  • A boolean attribute such as disabled={@busy} is rendered only when true.

Automatic escaping

HEEx escapes everything interpolated into the page: <script> becomes &lt;script&gt;. This stops cross-site scripting (XSS) by default.

HEEX
<p>{@comment.body}</p>
<%!-- if body is "<script>alert(1)</script>", the page shows it as text --%>

To output trusted HTML you must opt in with Phoenix.HTML.raw/1, which marks a string as safe:

HEEX
{raw(@post.rendered_html)}

Only call raw/1 on HTML you generated or sanitized yourself, such as the output of a Markdown renderer that strips scripts. Never use it on user input directly.

Conditionals and loops

HEEX
<p :if={@posts == []}>No posts yet.</p>

<ul :if={@posts != []}>
  <li :for={post <- @posts}>
    <.link navigate={~p"/posts/#{post}"}>{post.title}</.link>
  </li>
</ul>

:if and :for are special attributes that work on any tag and keep the markup tidy. Use :for with a filter or index when needed: :for={{post, i} <- Enum.with_index(@posts)}. For if/else or case use block form:

HEEX
<%= if @user do %>
  <p>Welcome back, {@user.name}</p>
<% else %>
  <.link href={~p"/login"}>Log in</.link>
<% end %>

Comments, attributes and whitespace

HEEX
<%!-- This comment is removed from the output --%>
<!-- This HTML comment is sent to the browser -->

Spread several attributes at once with {@rest} syntax (<input {@rest} />), and note that HEEx validates your markup: a missing closing tag is a compile error, not a broken page.

Layouts at a glance

Every page is wrapped by a root layout (the <html>, <head> and scripts) and an app layout (header, flash, main container). The content of your template appears where {@inner_content} (root) or {render_slot(@inner_block)} (app) sits. We configure layouts in layouts and core components.

Common mistakes

  • Writing @post.title when the assign is missing: the template raises a KeyError naming the assign. Always pass what the template uses.
  • Quoting an expression: class="{@cls}" prints the text {@cls}; write class={@cls}.
  • Forgetting the <% end %> of a block.
  • Putting business logic in templates. Compute values in the controller or a context and pass them in.

Escaping, modeled

JS Escape by default, raw by choice

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

No output.

Interpolated values are escaped unless wrapped in the Safe marker, the same contract as raw/1.

Loops and :if, modeled

JS Rendering a list with :for and :if

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

No output.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What happens to <script> inside an interpolated value in HEEx?

    HEEx escapes interpolated values by default, which prevents XSS.
  2. 2. Which line is correct for a dynamic CSS class?

    Attribute expressions go in braces without quotes: class={@cls}.
  3. 3. When is raw/1 appropriate?

    raw/1 disables escaping, so use it only on trusted or sanitized HTML.
  4. 4. What does :for={post <- @posts} on an <li> do?

    :for repeats the tag for each element of the enumerable.
  5. 5. How does the controller's render(conn, :index, posts: posts) reach the template?

    Keyword arguments become assigns, read with @name inside the template.

Summary

  • HEEx is HTML plus Elixir: for values, @name for assigns, :if and :for for logic.
  • Output is escaped by default; raw/1 is an explicit, dangerous opt-out.
  • Templates are embedded into a ...HTML module and receive the controller's assigns.
  • Keep logic out of templates and compute values beforehand.

Next: Function components and slots

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ị.