36

One way:

javascript_tag do
  == "var all_product_ids = #{existing_ids.to_json};"
  == "var products_json   = #{@filter.data.to_json};"

or:

= %Q{
var all_product_ids = #{existing_ids.to_json};
var products_json   = #{@filter.data.to_json};
}

are there any better solutions for this?

Nowaker
  • 12,154
  • 4
  • 56
  • 62
wkang
  • 411
  • 1
  • 6
  • 12

7 Answers7

84

In Slim

javascript:
  var all_product_ids = "#{existing_ids.to_json}";
  var products_json   = "#{@filter.data.to_json}";
stonean
  • 1,218
  • 1
  • 9
  • 7
21
javascript:
  var all_product_ids = #{raw existing_ids.to_json};
  var products_json   = #{raw @filter.data.to_json};
lidaobing
  • 1,005
  • 13
  • 26
18

From https://github.com/slim-template/slim Text Interpolation paragraph

SLIM escapes HTML by default. To avoid the same use #{{content}} for #{content}

Karthik M
  • 181
  • 1
  • 2
10

what i prefer to do, is to keep all the javascript in a separate file.

for example, i would do it as follows(jquery):

in your layout:

...

<body data-product-ids="<%= existing_ids.to_json %>"
      data-products-json="<%= @filter.data.to_json %>">

.. in js:

// create your application namespace
$.myapp = {};
$.myapp.allProductIds = $.parseJSON( $('body').attr('data-product-ids') );
$.myapp.products = $.parseJSON( $('body').attr('data-products-json') );

so, you'll then use it in js like so:

$.myapp.allProductIds
Vlad Khomich
  • 5,820
  • 1
  • 27
  • 39
  • 1
    Thank you! But when you only need one or two lines js code, will you still use a separate file? – wkang Apr 16 '11 at 12:10
  • 2
    Well, yes, it's just for a "best practices" matter. But still, that makes your code more solid and better structed – Vlad Khomich Apr 18 '11 at 05:30
  • 2
    Why this is the accepted answer when this is an ERB/jQuery answer to a specific slim/javascript question... – Matthew Jul 01 '19 at 16:40
3

I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using Gon. This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems.

3

create a _your_erb_file_contain_javascript_code.erb first

And then in your slim file javascript: part:

#{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil}
Lane
  • 4,682
  • 1
  • 36
  • 20
2
javascript:
  var isAdmin = "#{current_user.admin? ? 1 : 0}";
MZaragoza
  • 10,108
  • 9
  • 71
  • 116
Lane
  • 4,682
  • 1
  • 36
  • 20