Skip to content

Facet (views)

Facet templates are HTML with Amethyst inside, in .facet files under app/views/. They’ll look familiar if you’ve used ERB. The difference is that Facet compiles them along with the rest of your app, so templates are type-checked too.

app/views/posts/index.facet
<%# locals: (posts: Array[Post]) %>
<h1>Posts</h1>
<% posts.each do |post| %>
<article>
<h2><%= link_to post.title, post_path(post) %></h2>
<p><%= post.excerpt %></p>
</article>
<% end %>
Tag Does
<% code %> Runs Amethyst code
<%= expression %> Inserts the value, HTML-escaped
<%== expression %> Inserts the value without escaping. You’d better be sure
<%# comment %> A comment, never sent to the browser

The first line of a template declares the locals it expects:

<%# locals: (post: Post, show_comments:: Bool = true) %>

render :show, post: post in a controller is checked against this declaration. Pass the wrong type, forget a local or misspell one, and the build fails. Rails added something like this as an optional magic comment in 7.1. In Facet it’s mandatory, because we’ve all met undefined method 'title' for nil.

app/views/layouts/application.facet wraps every page, and yield marks where the page goes:

app/views/layouts/application.facet
<%# locals: (title:: String = "Blog") %>
<!doctype html>
<html>
<head><title><%= title %></title></head>
<body>
<%= yield %>
</body>
</html>

Partials are templates whose names start with _, rendered with render:

<%= render "posts/_card", post: post %>
Helper Produces
link_to text, path An <a> element
form_with model: record do |form| … end A form bound to a record
image_tag path An <img> element
time_ago(time) “3 minutes ago”
pluralize(count, word) “1 post”, “2 posts”