在Rails的Mailer视图中获取格式 [英] Getting Format in Mailer View in Rails

查看:90
本文介绍了在Rails的Mailer视图中获取格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails应用程序中,我在Mailer视图中使用一种方法来创建一个链接,该链接根据 html text 格式。

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 )

根据格式,它要么创建锚点< a> 标记对于html还是只显示 url 为文本。

Depending on the format, it either creates an anchor <a> tag for html or just shows the url for text.

因此对于每个Mailer方法,我都有两个视图:

So for each Mailer method, I have two views:

myemail.html.erb
myemail.text.erb

myemail.html.erb 中,我使用 mailer_link_to( http:/ /ntwrkapp.com, ntwrk, html)

myemail.text.erb 中,我使用 mailer_link_to( http:// ntwrkapp .com, ntwrk, text)

我想知道的是,是否可以确定格式是什么,所以我不必重复太多自己并指定 html每次都是 文本

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.

如果我的视线正常/ controller,我会做类似 request.format 的操作,但是 request 对象在Mailer视图中不可用。

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.

谢谢!

推荐答案

使用 self .formats



其他答案中发现每个视图都有一个 .formats 方法,该方法包含将用于部分显示和诸如此类的格式数组:

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]

因此,您可以使用它手动将当前格式传递给 mailer_link_to 这样的方法:

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 )

要抢先说我应该只需使用局部格式,它将自动通过正确的格式,我同意!为了简化问题,我简化了示例,但是在我的实际用例中,确实需要手动获取Mailer View的格式。谢谢您的帮助。

这篇关于在Rails的Mailer视图中获取格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆