How to use the Sinatra Haml helper inside the model?

In one of my models, I have a method that sends an email. I would like to tag this email through a Haml file, which is stored along with my other submissions.

Is there a way to call a Sinatra HAML helper from a model? If not, I will need to invoke Haml directly like this:

@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 @name ?

+4
source share
3 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!

+5
source

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" 

self above is the render method passed here, providing the area in which the template will be evaluated.

Of course, you can put the Haml template string either directly, as described above, or by reading from a file:

 Haml::Engine.new(IO.read(myfile)).render(self) 
+4
source

I'm not sure that HAML is a good choice for email. I would use ERB or Erubis because they allow more rendering, which will work well to populate variable fields.

If you create an HTML attachment in a MIME email address, then HAML would be a good choice for this part of the message, but again, I would probably grab ERB or Erubis to create both the body of the MIME and the HTML part.

If you do not want to use ERB / ​​Erubis, look at the usual "here-to" line, for example:

 body = <<EOT Dear #{whoever}, You owe me #{ lots_of_dollars } bucks. Pay by #{ when_i_need_it } or I'll shave my yak. Your truly, #{ who_i_am } EOT 

I think HAML is a great tool, but in my opinion it is not suitable for this situation.

+1
source

Source: https://habr.com/ru/post/1345385/


All Articles