Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have an optional local variable in a partial template in rails?

I was thinking that at the top of my partial I would have something like this

<% optional_width = default_value unless (defined? optional_width) 

But I've had inconsistent results with this, I'm thinking this is not a good way to do this. What is the "correct" way to do this in rails?

like image 593
Janak Avatar asked Mar 05 '10 08:03

Janak


People also ask

How do you pass locals in partials?

The way we use locals with a partial is similar to how we pass arguments into a method. In the locals Hash , the post_author: key is the argument name, and the value of that argument, @author , is the value stored as post_author and passed into the method.

What is Local_assigns?

local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not. Here you render a partial with some values, the headline and person will become accessible with predefined value.


2 Answers

Read the Passing local variables to sub templates section in the ActionView::Base docs

Basically it says you should use this pattern:

<% if local_assigns.has_key? :headline %>
  Headline: <%= headline %>
<% end %>

For you, this might translate to something like:

<div style="width: <%= local_assigns.has_key?(:optional_width) ? optional_width : 500 %>px;">
  <!-- filler -->
</div>

important!

According to the docs

Testing using defined? headline will not work. This is an implementation restriction.

like image 148
maček Avatar answered Oct 06 '22 00:10

maček


Although not exactly equivalent to your code, that's usually done with || operator.

<%  optional_width ||= default_value  %>

This is equivalent to optional_width = optional_width || default_value. Due to shot-circuit evaluation, if optional_with is "true", i.e. it's defined, and not nil, the right-hand part becomes equal to it, and default_value is not even computed. Otherwise, right-hand part would be equal to default_value. That's essentially what you want to do.

Ok, I admit that it may not work for partial's locals. The particular situation I can imagine is that if in first render call the optional_width variable was set to some value, and in the consequent call to render it is not mentioned at all while keeping its value from the first run. Can't do such a check right now, though.

like image 24
P Shved Avatar answered Oct 06 '22 01:10

P Shved