Class Public methods
register_template_handler Link
Register an object that knows how to handle template files with the given extensions. This can be used to implement new template types. The handler must respond to :call, which will be passed the template and should return the rendered template as a String.
ActionView::Template.register_template_handler :foo, FooHandler
Instance Public methods
local_assigns Link
Returns a hash with the defined local variables.
Given this sub template rendering:
<%= render "application/header", { headline: "Welcome", person: person } %>
You can use local_assigns in the sub templates to access the local variables:
local_assigns[:headline] # => "Welcome"
Each key in local_assigns is available as a partial-local variable:
local_assigns[:headline] # => "Welcome" headline # => "Welcome"
Since local_assigns is a Hash, it’s compatible with Ruby 3.1’s pattern matching assignment operator:
local_assigns => { headline:, **options } headline # => "Welcome" options # => {}
Pattern matching assignment also supports variable renaming:
local_assigns => { headline: title } title # => "Welcome"
If a template refers to a variable that isn’t passed into the view as part of the locals: { ... } Hash, the template will raise an ActionView::Template::Error:
<%# => raises ActionView::Template::Error %> <% alerts.each do |alert| %> <p><%= alert %></p> <% end %>
Since local_assigns returns a Hash instance, you can conditionally read a variable, then fall back to a default value when the key isn’t part of the locals: { ... } options:
<% local_assigns.fetch(:alerts, []).each do |alert| %> <p><%= alert %></p> <% end %>
Combining Ruby 3.1’s pattern matching assignment with calls to +Hash#with_defaults+ enables compact partial-local variable assignments:
<% local_assigns.with_defaults(alerts: []) => { headline:, alerts: } %>
<h1><%= headline %></h1>
<% alerts.each do |alert| %>
<p><%= alert %></p>
<% end %>
By default, templates will accept any locals as keyword arguments and make them available to local_assigns. To restrict what local_assigns a template will accept, add a locals: magic comment:
<%# locals: (headline:, alerts: []) %> <h1><%= headline %></h1> <% alerts.each do |alert| %> <p><%= alert %></p> <% end %>
Read more about strict locals in Action View Overview in the guides.