How to use Sinatra's Haml-helper inside a model?
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)
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 }
EOT
I think HAML is a great tool, but, in my opinion, it's not the best fit for this situation.
精彩评论