module Roda::RodaPlugins::RenderEach

  1. lib/roda/plugins/render_each.rb

The render_each plugin allows you to render a template for each value in an enumerable, returning the concatention of all of the template renderings. For example:

render_each([1,2,3], :foo)

will render the foo template 3 times. Each time the template is rendered, the local variable foo will contain the given value (e.g. on the first rendering foo is 1).

If you provide a block when calling the method, it will yield each rendering instead of returning a concatentation of the renderings. This is useful if you want to wrap each rendering in something else. For example, instead of calling render multiple times in a loop:

<% [1,2,3].each do |v| %>
  <p><%= render(:foo, locals: {foo: v}) %></p>
<% end %>

You can use render_each, allowing for simpler and more optimized code:

<% render_each([1,2,3], :foo) do |text| %>
  <p><%= text %></p>
<% end %>

You can also provide a block to avoid excess memory usage. For example, if you are calling the method inside an erb template, instead of doing:

<%= render_each([1,2,3], :foo) %>

You can do:

<% render_each([1,2,3], :foo) %><%= body %><% end %>

This results in the same behavior, but avoids building a large intermediate string just to concatenate to the template result.

When passing a block, render_each returns nil.

You can pass additional render options via an options hash:

render_each([1,2,3], :foo, views: 'partials')

One additional option supported by is :local, which sets the local variable containing the current value to use. So:

render_each([1,2,3], :foo, local: :bar)

Will render the foo template, but the local variable used inside the template will be bar. You can use local: nil to not set a local variable inside the template. By default, the local variable name is based on the template name, with any directories and file extensions removed.

Methods

Public Class

  1. load_dependencies

Constants

ALLOWED_KEYS = [:locals, :local].freeze  

Public Class methods

load_dependencies(app)

Load the render plugin before this plugin, since this plugin calls the render method.

[show source]
   # File lib/roda/plugins/render_each.rb
67 def self.load_dependencies(app)
68   app.plugin :render
69 end