Tag Archives: yml

Middleman Dynamic Content in Single Template

I’ve been playing a little with middleman (http://middlemanapp.com/) to build some simple static sites lately and have been looking at how to do this a little more dynamically.

More precisely, I wanted to be able to deliver unique content or yml data files to the same html.erb template file. For my use case I was attempting to get multiple slightly different versions of the same page, same layout but variations on the same content. Rather than recreating every page over again I just wanted to allow a writer to be able to copy paste the yml file and update it. Turns out it’s pretty simple.

The example I’ll go through is to have three pages for 3 people (Bob, Joe & Linda). But instead of creating a 1 to 1 relationship between the yml and html.erb files:

data/bob.yml => source/bob.html.erb
data/joe.yml => source/joe.html.erb
data/linda.yml => source/linda.html.erb

I’ll have 3 yml files and 1 html.erb file:

data/bob.yml, data/joe.yml, data/linda.yml, source/person.html.erb

What this will allow me to do is 2 simple things: 1. I can more easily add additional people, just copy the yml file and update their content. 2. use a single template (not layout) for all of those people without having to update each of them.

Here are the 3 sets of files needed for the example, you can do this with any fresh middleman app that you have just initialized.

config.rb

["bob", "joe", "linda"].each do |person|
    proxy "/#{person}.html", "/person.html", :locals => { :person => person }, :ignore => true
end

This will configure the proxy to route each of your people to the template. The first line is effectively whitelisting which urls of people will be passed to my template. The second line then has 4 arguments passed to the proxy.

  1. “/#{person}.html” – this is the url to proxy, the #{person} is replaced with the names you listed in the first line
  2. “/person.html” – this is the template file found in the source directory that will render each of your pages
  3. :locals => { :person => person } – create a variable called person with the above persons name in it, you can use this to uniquely access the data for each person
  4. :ignore => true – ensure that person.html isn’t a page of its own

source/person.html.erb

Name: <%= data.people[person].name %>
<br/>
Age: <%= data.people[person].age %>

A very simple template file that will output our data for each person. You can see that we are using the person variable name to get the content dynamically. This will load the data/people/bob.yml file or the data/people/linda.yml for example.

data/people/bob.yml

name: Bob
age: 36

Finally, our data file for bob, you can copy paste this into as many different people as necessary.

View my full example on GitHub (https://github.com/wesdeboer/middleman-example)