2008
08.05

For Inshaker, we needed a templating mechanism for pages sharing the same design. We also wanted the pages to be static (for performance reasons). We did not need them to be generated on-the-fly.
ERB was an ideal option for such a purpose. It allows us to generate all (75+) static pages when we need to make an update.
It is also very simple in terms of use:

1. You create a template for your page (template.rhtml)


<html>
<head>
	<title><%= @title %></title>
</head>
<body>
	This page was generated by <%= @name %> on <%= Time.now.to_s %>.
	<ul>
	<% @tags.each do |tag| %>
	<li><%= tag %></li>
	<% end %>
	</ul>
</body>
</html>

2. You create a ruby class which is bound to the template and run erb (erb_test.rb)


require 'rubygems'
require 'erb'

class MyPage
  def initialize(hash)
    @title = hash[:title] + " - that's what I mean"
    @name = hash[:name]
    @tags = hash[:tags]
  end

  def get_binding
    binding
  end
end

# Instantiate ERB with the instance of that class and flush the output
template = File.open("template.rhtml").read
renderer = ERB.new(template)
page     = MyPage.new({:title => "ERB rules",
                       :name => "Ninja",
                       :tags => ["ruby", "erb", "html", "example"]})

File.open("mypage.html", "w+") { |html|
    html.write renderer.result(page.get_binding)
}

Of course, this is just a basic usage example. ERB shows its power when there are A LOT of pages to be generated, not a single one ;-)
I should have a closer look at SproutCore since they seem to be using the same principle for views compilation.

12 comments so far

Add Your Comment
  1. [...] vim to highlight.js. And now I am the first ever person using it in the blog Here you can see some ruby code highlighting and there goes some JavaScript. I’ve also tested it with CSS (looks just fine, trust me). [...]

  2. Видел уже где то…

  3. Однако

  4. Хм

  5. äà íîðì…

  6. axaxa…

  7. 32423 …

  8. vim to very

    Good post

  9. bbb

  10. vim to very