Goulven
Goulven

Reputation: 889

How to provide defaults value for partial parameters in Rails?

I need to render a shared partial which can receive a few parameters from several views, but I don't want to pass all parameters everytime. If I call the template without all parameters, I get an error.

Is there a way to define default values for parameters, only if they haven't been defined when calling render 'name_of_partial?

Upvotes: 7

Views: 2841

Answers (3)

yenshirak
yenshirak

Reputation: 3106

With Rails >=7.1 you can define strict locals with a magic comment:

<%# locals: (my_param: "default value") -%>

https://guides.rubyonrails.org/action_view_overview.html#strict-locals

Upvotes: 5

Goulven
Goulven

Reputation: 889

After reading the docs, and some head scratching, I was able to define default values for parameters not passed to the template.

# in views/shared/template.html.erb
<% my_param = 'default_value' unless binding.local_variable_defined?(:my_param) %>
# Now you can call the partial with or without setting `my_param`

# Now you can call the partial without parameters...
<%= render 'shared/my_template' %>
# ...or with parameters
<%= render 'shared/my_template', my_param: 'non-default value' %>

Tested with Ruby 2.3.1 and upwards.

This handles passing false or nil as a parameter without it being overwritten by the default value. The accepted answer does not handle this case.

Upvotes: 3

DannyB
DannyB

Reputation: 14776

This should do the trick:

<% my_param ||= 'default value' %>

A partial that contains this can be rendered with or without providing my_param.

Upvotes: 12

Related Questions