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?
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With