15

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?

5 Answers 5

5

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Why is true a string, but false a boolean?
@HunterStevens no good reason... probably just because it worked :) fixed now.
2

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" : ""}

Comments

0

I've interpolated the Ruby/HAML variable into explicit JS true or false for JS condition like this:

$("#cancel").click( function() {
  if (#{ !!my_flag_variable })
    window.location.href = "./";
  else
    $("#dialog").hide();
} );

Comments

-1

I've accomplished this via a = yield :foot_scripts call in my layout, then then:

= if condition
  - content_for :foot_scripts do
    - render :partial => "page_specific_javascript"  

in my views — that way I can ensure the Javascript is executed exactly where I want it to be in the DOM (AFTER everything else), and maintain it in a separate file, which is vastly cleaner. Getting script out of your view files? GOOD!

Comments

-3

That's pretty much right.

The other option is you could put it in a .js.erb partial and render that from your haml view.

Then you can just do

// do something
<% if condition == true %>
  // do something else
<% end %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.