Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate ruby if statement in haml javascript block

This is the code I currently have:

:javascript
    // do something
- if current_user.role? :client
    :javascript
        //do something else

It's obviously not very clean since I'm repeating the :javascript haml filter. I'd like to avoid that, but I don't know how to properly write a Ruby "if" statement inside a HAML :javascript block.

I know how to interpolate variables with #{}, but how do you do the same for whole if/for/etc. statements?

like image 355
Sacha Avatar asked Jun 22 '12 01:06

Sacha


2 Answers

I do this:

if(#{params[:param_to_check_for].blank? ? "true" : "false"})

In the above case, the condition is params[:param_to_check_for].blank?.

It renders the JavaScript as either: if(false) or if(true)

like image 55
Caleb Avatar answered Sep 18 '22 20:09

Caleb


I haven't tried it, but I'd think you could do

:javascript
    // do something
- if current_user.role? :client
    ="//do something else"

(As in the second example here.)

For a very short bit of javascript, you could also try

:javascript
    // do something
    #{current_user.role? :client ? "//do something else" : ""}
like image 23
Jacob Mattison Avatar answered Sep 17 '22 20:09

Jacob Mattison