diff --git a/README.md b/README.md index ecb3aa8..0eb6cda 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rails/render-an-alternative-action-mailer-template.md b/rails/render-an-alternative-action-mailer-template.md new file mode 100644 index 0000000..7be3644 --- /dev/null +++ b/rails/render-an-alternative-action-mailer-template.md @@ -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)