问题
In my Rails app, I use a method in my Mailer views for creating a link that takes a format param based on whether it's in html or text format.
mailer_link_to( url, link_text, format )
Depending on the format, it either creates an anchor <a> tag for html or just shows the url for text.
So for each Mailer method, I have two views:
myemail.html.erb
myemail.text.erb
In myemail.html.erb, I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "html" ).
In myemail.text.erb I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "text" ).
What I'm wondering is if I can determine what the format is so I'm not having to duplicate myself so much and specify "html" or "text" each time.
If I was in a normal view/controller, I would do something like request.format but the request object isn't available in the Mailer views.
Thanks!
回答1:
Use self.formats.
Discovered in this other answer that each view has a .formats method that contains an Array of formats that will get used in partials and whatnot:
self.formats #=> [:text]
So, you can use this to manually pass the current format to the mailer_link_to method like so:
mailer_link_to( "http://ntwrkapp.com", "ntwrk", self.formats.first )
And to preempt anybody saying I should just use a partial, which will automatically pass the correct format, I agree! I simplified my example for the sake of asking the question but in my actual use case I really did need to get the Mailer View's format manually. Thanks for trying to help, tho.
来源:https://stackoverflow.com/questions/47459724/getting-format-in-mailer-view-in-rails