How to prevent style duplication in Rails HTML emails?

六月ゝ 毕业季﹏ 提交于 2019-12-07 20:06:43

问题


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?

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


回答1:


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.

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.

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"

Its contents could look something like this:

<!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>

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

This approach keeps your content "DRY".



来源:https://stackoverflow.com/questions/12700699/how-to-prevent-style-duplication-in-rails-html-emails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!