Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 665
Goulven Avatar asked Dec 24 '22 01:12

Goulven


2 Answers

This should do the trick:

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

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

like image 176
DannyB Avatar answered Dec 25 '22 14:12

DannyB


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.

like image 30
Goulven Avatar answered Dec 25 '22 13:12

Goulven