1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Render An Alternative ActionMailer Template as a Rails til

This commit is contained in:
jbranchaud
2020-12-28 15:35:53 -06:00
parent 0588aeed40
commit 85ee6f928c
2 changed files with 49 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_984 TILs and counting..._
_985 TILs and counting..._
---
@@ -636,6 +636,7 @@ _984 TILs and counting..._
- [Read In Environment-Specific Config Values](rails/read-in-environment-specific-config-values.md)
- [Read-Only Models](rails/read-only-models.md)
- [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md)
- [Render An Alternative ActionMailer Template](rails/render-an-alternative-action-mailer-template.md)
- [Rescue From](rails/rescue-from.md)
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)
- [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md)

View File

@@ -0,0 +1,47 @@
# Render An Alternative ActionMailer Template
The convention for Rails's ActionMailer is to render the view template that
corresponds to the mailer class's name and the specific action.
For instance, the `welcome_email` method in the `RegistrationMailer` class will
correspond to the `app/views/registration_mailer/welcome_email.html.erb` view.
This convention can be overridden. By passing, the `template_name` and
`template_path` arguments as options to the `mail` method, you can tell the
mailer to render a different template.
```ruby
class RegistrationMailer < ActionMailer::Base
def welcome_email
# mail setup ...
mail(to: @user.email,
subject: 'Welcome!',
template_name: 'new_welcome')
end
end
```
This will look for and use the
`app/views/registration_mailer/new_welcome.html.erb` template.
Also including the `template_path` option will alter the path to the named
template:
```ruby
class RegistrationMailer < ActionMailer::Base
def welcome_email
# mail setup ...
mail(to: @user.email,
subject: 'Welcome!',
template_path: 'v2_mailer_templates',
template_name: 'new_welcome')
end
end
```
This will look for the `app/views/v2_mailer_templates/new_welcome.html.erb`
template.
[source](https://guides.rubyonrails.org/action_mailer_basics.html#mailer-views)