Take the 2-minute tour ×

In one of my models I have a method that sends an email. I'd like to mark up this email via a Haml file that's stored together with my other views.

Is there a way to call Sinatra's HAML-helper from within a model? If not, I will need to call Haml directly like so:

@name = 'John Doe'

Is there a way for the Haml template to have access to the @name instance variable?

share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

Try something like this:

tmpl = Tilt.new("#{MyApplication.views}/email.haml")
tmpl.render(self) # render the template with the current model instance as the context

Hope this helps!

share|improve this answer
Yep, did the trick. Thanks a bunch! –  Marc Mar 27 '11 at 0:29
add comment

Without using Tilt, you can simply do this in Haml:

require 'haml'
@name = 'John Doe'
html = Haml::Engine.new('%p= @name').render(self)
#=> "<p>John Doe</p>\n"

The self above passed to the render method is the key here, providing the scope in which the template will be evaluated.

Of course, you can supply the Haml template string either directly, as above, or by reading it from file:

share|improve this answer
add comment

I'm not sure HAML is a good choice for email. I'd use ERB or Erubis because they allow more freeform rendering which would work well for filling in variable fields.

If you're creating an HTML attachment to a MIME email then HAML would be an ok choice for that part of the message, but, again, I'd probably grab ERB or Erubis to create both the text part of the MIME body, and the HTML part.

If you don't want to use ERB/Erubis, look at using a normal "here-to" string such as:

body = <<EOT
Dear #{whoever},

You owe me #{ lots_of_dollars } bucks. Pay by #{ when_i_need_it } or I'll shave my yak.

Your's truly,

#{ who_i_am }

I think HAML is a great tool, but, in my opinion, it's not the best fit for this situation.

share|improve this answer
Thanks for your thoughts and solution. In my case HTML-only emails are good enough so that's why I opted for HAML. That said, it's nice to know the other solutions for future reference. –  Marc Mar 27 '11 at 0:31
I can understand that. Just as a reminder, a lot of people don't like HTML email, or can't even read it because their MUA doesn't support it. It's one of the big arguments against HTML email, or at least for MIME which is supposed to contain a text-only body. –  the Tin Man Mar 27 '11 at 0:45
Haml is a perfect solution for a plain text email too, if your app is already using Haml for rendering views. Just use the :plain filter and you're done. My 0.2CAD –  Florin May 5 '12 at 19:37
add comment

Your Answer


