Search code examples
ruby-on-railsrubyslim-lang

How to embed dynamic Ruby code to "javascript" section in Slim templates?


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?


Solution

  • 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