Skip to content

Commit 85ee6f9

Browse files
committed
Add Render An Alternative ActionMailer Template as a Rails til
1 parent 0588aee commit 85ee6f9

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_984 TILs and counting..._
13+
_985 TILs and counting..._
1414

1515
---
1616

@@ -636,6 +636,7 @@ _984 TILs and counting..._
636636
- [Read In Environment-Specific Config Values](rails/read-in-environment-specific-config-values.md)
637637
- [Read-Only Models](rails/read-only-models.md)
638638
- [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md)
639+
- [Render An Alternative ActionMailer Template](rails/render-an-alternative-action-mailer-template.md)
639640
- [Rescue From](rails/rescue-from.md)
640641
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)
641642
- [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Render An Alternative ActionMailer Template
2+
3+
The convention for Rails's ActionMailer is to render the view template that
4+
corresponds to the mailer class's name and the specific action.
5+
6+
For instance, the `welcome_email` method in the `RegistrationMailer` class will
7+
correspond to the `app/views/registration_mailer/welcome_email.html.erb` view.
8+
9+
This convention can be overridden. By passing, the `template_name` and
10+
`template_path` arguments as options to the `mail` method, you can tell the
11+
mailer to render a different template.
12+
13+
```ruby
14+
class RegistrationMailer < ActionMailer::Base
15+
def welcome_email
16+
# mail setup ...
17+
18+
mail(to: @user.email,
19+
subject: 'Welcome!',
20+
template_name: 'new_welcome')
21+
end
22+
end
23+
```
24+
25+
This will look for and use the
26+
`app/views/registration_mailer/new_welcome.html.erb` template.
27+
28+
Also including the `template_path` option will alter the path to the named
29+
template:
30+
31+
```ruby
32+
class RegistrationMailer < ActionMailer::Base
33+
def welcome_email
34+
# mail setup ...
35+
36+
mail(to: @user.email,
37+
subject: 'Welcome!',
38+
template_path: 'v2_mailer_templates',
39+
template_name: 'new_welcome')
40+
end
41+
end
42+
```
43+
44+
This will look for the `app/views/v2_mailer_templates/new_welcome.html.erb`
45+
template.
46+
47+
[source](https://guides.rubyonrails.org/action_mailer_basics.html#mailer-views)

0 commit comments

Comments
 (0)