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
?
This should do the trick:
<% my_param ||= 'default value' %>
A partial that contains this can be rendered with or without providing my_param
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With