{"id":2166,"date":"2011-06-16T16:22:38","date_gmt":"2011-06-16T19:22:38","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=2166"},"modified":"2011-06-16T16:22:38","modified_gmt":"2011-06-16T19:22:38","slug":"multipart-templates-with-markerb","status":"publish","type":"post","link":"https:\/\/blog.plataformatec.com.br\/2011\/06\/multipart-templates-with-markerb\/","title":{"rendered":"Multipart templates with Markerb"},"content":{"rendered":"

When writing Crafting Rails Applications<\/a>, I knew exactly which parts from Rails I wanted to talk about. However, I didn’t want the book to simply describe how everything works, I actually wanted everyone to build something useful from each part of Rails.<\/p>\n

One of the hardest areas to come up with an useful tool as example was the template handlers. Template handlers are responsible for template compilation and the canonical examples are: ERb and Haml. Obviously, creating something like ERb or Haml from scratch would require a lot of code beyond the Rails integration so it wasn’t an option. On the other hand, tools that simply render rdoc or markdown templates would be too simple and there are already plenty of gems doing the same out there.<\/p>\n

So I started playing with some options. The first one was something like Why’s Markaby<\/a> but that would still require a good amount of code (albeit much less than ERb). Next, I have played with something called YERb (YAML + ERb)<\/a> which was an interesting hack but too slow to be of any use. I was almost planning to remove the chapter about template handlers when it finally came to me the idea of markerb<\/strong>: markdown + erb (in the book, we did a wordplay and called merb<\/strong>). While the idea was simple and easy to implement, it had a great use case: multipart templates.<\/p>\n

With Markerb<\/strong>, you can create one template for ActionMailer<\/strong> and it will be delivered both as text and HTML. So there is no need to maintain two templates. You write it in markdown, which is delivered as text, but also rendered to be delivered as HTML. Recently, I have crafted Markerb in its own gem so everyone can use it<\/a>.<\/p>\n

How to use?<\/h3>\n

The usage is quite simple. Assuming you have a notifier as below:<\/p>\n

class Notifier < ActionMailer::Base\r\n  def contact(recipient)\r\n    @recipient = recipient\r\n    mail(:to => @recipient, :from => \"john.doe@example.com\") do |format|\r\n      format.text\r\n      format.html\r\n    end\r\n  end\r\nend<\/pre>\n

If you create a template at app\/views\/notifier\/contact.markerb<\/code>:<\/p>\n

Multipart templates **rock**, right <%= @recipient %>?!<\/pre>\n

It will generate two parts, one in text and another in HTML when delivered. And that is it! Before we finish, here are a few things you might need to know:<\/p>\n