Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: check if a local variable exists and is true in a partial

In a partial, I want to add a class only if the is_embedded local variable was passed in and is true. How can I check this?

Currently I check if is_embedded is true like this:

_some_partial.html.erb

<section 
  id="view-dashboard" 
  class="<%= "embedded" if is_embedded %>"
>

However this gives an error if is_embedded is not passed in: undefined local variable or method 'is_embedded'.

Do I always need to pass it in? Or is there a way I can check if it both exists and is true without having errors if it doesn't exist.

like image 798
Don P Avatar asked Apr 11 '14 16:04

Don P


3 Answers

You can check the local_assigns hash, which includes the passed locals.

<section 
  id="view-dashboard" 
  class="<%= 'embedded' if local_assigns[:is_embedded] %>"
>
like image 58
vee Avatar answered Nov 09 '22 23:11

vee


when rending the partial do this
<%= render partial: "some_partial", locals: {is_embedded: true} %>

#_some_partial.html.erb
<%
 #locals
 is_embedded ||= false
%>
<section
id="view-dashboard"
class="<%= "embedded" if is_embedded %>">hhd</section>
like image 36
Uchenna Avatar answered Nov 09 '22 23:11

Uchenna


You can check this -

if defined?(is_embedded) && is_embedded

this will check if is_embedded defined and it is true

like image 6
LHH Avatar answered Nov 10 '22 00:11

LHH