CodyBugstein
CodyBugstein

Reputation: 23322

How can I conditionally include some Javascript in an html.slim file, as part of a larger Ruby on Rails project?

I want my page to render some Javascript, conditional on a variable from the Rails environment. I must have everything in this one file, because of other build tooling constraints.

Eseentially I am trying to get this working:

= javascript:
     console.log('My javascript goes in this area....');
     <% if myCondition %>
          console.log('Render the JS in here is myCondition is true')
     <%end>

However, when I try this, I get errors that < is not a valid character.

Upvotes: 2

Views: 1525

Answers (2)

chumakoff
chumakoff

Reputation: 7044

 javascript:
   console.log('My javascript goes in this area....');

 - if myCondition
   javascript:
      console.log('Render the JS in here is myCondition is true')

Also, this question might be useful: ruby inside javascript block [slim template]

Upvotes: 2

leafeve
leafeve

Reputation: 150

you cannot use <% ... %> in your javascript

If you want to use rails data, try e.i

var form_id = "form"+ #{{@product.id.to_json}};

Another way, you should be use ajax( it was mean your_action.js.slim ), see i.e bellow

create.js.slim

- if @product.errors.present?
  | toastr["error"]("#{@product.errors.full_messages[0]}");
- else
  | toastr["success"]("Created successfully!");

Upvotes: 0

Related Questions