Skip to content
Perry Hertler edited this page Aug 24, 2022 · 9 revisions

There are a few ways to re-use templates:

Partial

partial is used to access the representation of another object for use in node:

object @post

node :categories do |post|
  post.categories.map do |category| 
    partial("categories/show", :object => category) 
  end
end

Extends

extends is used to inherit from another template:

object @post

child :categories do
  extends "categories/show"
end

The except option can be provided to exclude attributes from the parent template.

# products/show.rabl
attributes :name, :dimensions, :weight, :price

# free_products/show.rabl
extends "products/show", except: :price

You can also pass an object to extends, for example:

node :car do
  extends "cars/show", object: car
end

This can come in handy if you're rendering templates from different contexts and the method cannot be inferred.

When to use Partials and Extends together

partial allows you to reuse templates for multiple objects and extends allows you to reuse templates from multiple templates.

# users/show.rabl
object @presentation

node :blogger do
  partial "writers/info", object: presentation.blogger
end
node :author do
  partial "writers/info", object: presentation.author
end

# writers/_info.rabl
object @writer  # ignored when used as a partial so I usually don't specify it
attributes :name, :first_published_date, :birth_date, :death_date
child :publications do
  extends "publications/public"
end

# publications/public.rabl
attributes :title, :publication_date, :publisher

# publications/show.rabl
object @publication
extends "publications/public"