I am using Ruby on Rails 3.0.10 and I would like to pass some parameters to the default rendering method. That is, if I have a code like
def show
...
respond_to do |format|
format.html # This, by default, renders the 'show.html.erb' file
end
end
I would like to pass some parameters, maybe like (note: the following doesn't work)
def show
...
respond_to do |format|
# Here I would like to add some local objects that will be available in the 'show.html.erb' template file
format.html { render ..., :locals => { :content => { :value => 'Sample value' } } }
end
end
so that in the show.html.erb
template I can make something like:
<%=
content[:value]
# => 'Sample value'
%>
In few words, I would like to pass parameter values in the same way as made for partial template rendering related to the :locals
key:
render :partial,
:locals => {
:content => { :value => 'Sample value' }
}
How can I do that?
You can do exactly what you described. I looked it up here http://apidock.com/rails/ActionController/Base/render under the heading "Rendering a template" and gave it a whirl myself. You learn something new everyday.
You can simply do
def show
respond_to do |format|
format.html { render :locals => { :content => { :value => 'Sample value' } } }
end
end
I would consider why you need to do this instead of using instance variables. Maybe there is a better approach.
How about setting an instance variable?
# your_controller.rb
def show
@content_value = ...
end
# show.html.erb
<%= @content_value %>
Usually when we're working with actions show.html.erb
is an action
view rather than a partial
view, we're passing parameters via instance variables on the controller such as
def show
...
@foo = "bar"
respond_to do |format|
format.html
end
end
Now in the app/views/foos/show.html.erb
file, we have access to @foo
.
When rendering partials, there are a few ways to pass parameters:
This will render partial app/views/foos/_foo.html.erb
by default because it knows @foo
is of type Foo
. In it, you will have access to a foo
variable automatically.
<%= render @foo %>
Here we will render app/views/foos/_foo_details.html.erb
, and pass in an object. The object takes the name of the partial, so inside _foo_details.html.erb
we'll have access to a variable called foo_details
.
<%= render :partial => "foo_details", :object => @foo %>
Finally, and mostly related to your question, we'll render a partial called _foo_things.html.erb
and pass it some locals. In this case, you'd get a local variable called title
which you could work with.
<%= render :partial => "foo_things", :locals => {:title=> "Test 123"} %>
I hope that answers your question.
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