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.
在我的Rails应用程序中,我在我的Mailer视图中使用一种方法来创建一个链接,该链接根据格式参数是html还是文本格式。
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.
根据格式,它可以为html创建一个anchor 标签,或者只显示文本的URL。
So for each Mailer method, I have two views:
所以对于每个Mailer方法,我有两个视图:
myemail.html.erb
myemail.text.erb
In myemail.html.erb
, I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "html" )
.
在myemail.html.erb中,我使用mailer_link_to(“http://ntwrkapp.com”,“ntwrk”,“html”)。
In myemail.text.erb
I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "text" )
.
在myemail.text.erb中,我使用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.
我想知道的是,如果我可以确定格式是什么,所以我不必复制自己这么多,每次都指定“html”或“text”。
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.
如果我在普通的视图/控制器中,我会做类似request.format的事情但是请求对象在Mailer视图中不可用。
Thanks!
谢谢!
1 个解决方案
#1
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:
在另一个答案中发现,每个视图都有一个.formats方法,其中包含将在partials和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方法,如下所示:
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.
为了抢先说任何人说我应该使用部分,这将自动传递正确的格式,我同意!为了提出问题,我简化了我的例子,但在我的实际用例中,我确实需要手动获取Mailer View的格式。谢谢你试图帮忙,谢谢。
#1
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:
在另一个答案中发现,每个视图都有一个.formats方法,其中包含将在partials和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方法,如下所示:
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.
为了抢先说任何人说我应该使用部分,这将自动传递正确的格式,我同意!为了提出问题,我简化了我的例子,但在我的实际用例中,我确实需要手动获取Mailer View的格式。谢谢你试图帮忙,谢谢。