Displaying repeated Ruby ERB partials with dynamic content

Loop through JSON and spit out dynamic formatted HTML blocks using Ruby and Middleman

ruby,padrino,erb,middleman

Middleman is the easiest static site generator I've ever used. A one command install, a great boilerplate to get you going, and a solid system of templates, variables, dependency management, helpers, etc covers everything you need for an average front-end focused site. And while Middleman does a lot, it was a bit difficult for me to see how to tie all the various functionality together in order to render partials that had been passed variables, so I thought I'd jot down this tip.

If you have a repeating element on a page (in my case a series of 9 items in a grid that included a thumbnail and some text below them), you can tell middleman to loop through those items, and output a ruby ERB partial for each cycle of the loop. This is done as follows:


<% 9.times do |num| %>
  <%= partial "partials/partial-name" %>
<% end %>

and the partial:


<div class="listing">
  <img/>
  <article/>
</div>

where "partials/partial-name" is the path to the partial you want to include each time you loop.

For my partials though, I wanted each to contain a unique index, that I would pass from the template which was including the partial.

In order to do that, you can modify the above script as follows:


<% 9.times do |num| %>
  <%= partial("partials/partial-name", :locals => { :index => num } ) %>
<% end %>

Here, we are still calling the same partial, but we are using a ruby module called Padrino to pass it local (variables). Locals is an object, where each object pair consists of a variable name that your partial will have access to (in this case :index), and the value of that variable, in this case, "num" which we specified when running our loop: "9.times do |num|".

Now, in our partial, we can render out a unique ID:


<div id="listing<%= index %>" class="listing">
  <img/>
  <article/>
</div>