如何防止Rails HTML电子邮件中的样式重复? [英] How to prevent style duplication in Rails HTML emails?

查看:85
本文介绍了如何防止Rails HTML电子邮件中的样式重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建Rails HTML电子邮件,但是电子邮件的结构(页眉和页脚)在每一个中都是重复的。通常,这不是问题,但是对于内联样式而言,如果我想更改颜色似乎也可能是一个问题。我该如何将这些元素从每个文件中提取出来并放入一个文件中?

I am trying to build rails HTML emails, but the structure (header and footer) of the emails is duplicated in each one. Typically it's not a problem, but with the inline styles as well, it seems like it can be an issue if I want to change the color. How can I pull these elements out of each file and into one?

此外,是否有消除html.erb和text.erb文件之间文本重复的方法?

Also, is there anyway to eliminate the duplication of text between the html.erb and text.erb files.

推荐答案

一个简单的方法是引用几个局部。假设他们的名字是这样的:

A simple way to do it is to reference a couple of partials. Let's say they're named something like this:


  • _email_header.html.erb

  • _email_footer。 html.erb

然后,您可以在每封电子邮件中引用它们:

Then you can refer to them inside each of your emails:

<%= render :partial => 'email_header' %>
Blah, email-specific content here...
<%= render :partial => 'email_footer' %>

这可以工作,但仍会导致大量复制粘贴,尽管比原始粘贴要少内联完整结构的版本。解决此问题的一种更清洁的方法是为这些电子邮件设置自定义布局。

That will work, but will still lead to a bunch of copy-paste, albeit less than the original version with the full structure inlined. A cleaner way to manage this is to set up a custom layout for these emails.

布局和渲染 Rails指南 Action Mailer Rails指南是有用的背景知识(如果您以前没有做过的话)。

The "Layout and Rendering" Rails Guide and the layouts section of the "Action Mailer" Rails Guide are helpful backgrounders for this, if you haven't done this before.

您会从这些引用中看到,有多种方法可以在Action Mailer中调用布局(还有在邮件上下文之外的更多方法),但是采用一种示例用法,您可以在此处创建布局模板文件: app / views / layouts / {your_mailer_name} .html.erb 。例如, user_mailer.html.erb

You will see from those references that there are multiple ways to invoke a layout within Action Mailer (and more ways still, outside of a mail context), but to take one example usage, you can create a layout template file here: app/views/layouts/{your_mailer_name}.html.erb. E.g., "user_mailer.html.erb"

其内容可能类似于:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>My Fancy Email</title>
  </head>
  <body>
    <%= render :partial => 'email_header' %>
    <%= yield %>
    <%= render :partial => 'email_footer' %>
  </body>
</html>

请注意 yield 调用,这就是您的位置特定的电子邮件内容将呈现。

Note the yield call, that's where your specific email content will render.

这种方法可以使您的内容保持

This approach keeps your content "DRY".

这篇关于如何防止Rails HTML电子邮件中的样式重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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