Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Sinatra's Haml-helper inside a model?

Tags:

ruby

sinatra

haml

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'
Haml::Engine.new(File.read("#{MyApplication.views}/email.haml")).to_html

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

like image 452
Marc Avatar asked Mar 27 '11 00:03

Marc


2 Answers

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!

like image 63
namelessjon Avatar answered Sep 20 '22 12:09

namelessjon


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:

Haml::Engine.new(IO.read(myfile)).render(self)
like image 35
Phrogz Avatar answered Sep 21 '22 12:09

Phrogz