Rails: access controller instance variable in CoffeeScript or JavaScript asset file

前端 未结 6 1139
我寻月下人不归
我寻月下人不归 2020-12-01 01:19

In Rails 3.1 it is not possible to access controller instance variables in an asset js.erb or coffee.erb file using syntax such as <%= @foo %>, where @foo is set in the c

6条回答
  •  天命终不由人
    2020-12-01 02:14

    a couple of ways I have done this in the past

    put the data in hidden fields, access the data in js/coffee

    # single value
    <%= hidden_field_tag "foo_name", @foo.name, { :id => "foo-name" } %>
    $('#foo-name').val();
    
    # when the 'value' has multiple attributes
    <%= hidden_field_tag "foo", @foo.id, { :id => "foo", "data-first-name" => @foo.first_name, "data-last-name" => @foo.last_name } %>
    $foo = $('#foo')
    console.log $foo.val()
    console.log $foo.data("firstName")
    console.log $foo.data("lastName")
    

    another option: load data into js data structure in erb, access it from js/coffee

    <% content_for(:head) do %>
        
    <% end %>
    
    
    # coffee
    for foo in window.App.Data.fooList
        console.log "#{foo.id}, #{foo.first_name} #{foo.last_name}"
    

    I am not a big fan of constructing javascript data from ruby in erb like this, something about it just feels wrong - it can be effective though

    and another option: make an ajax call and get the data on-demand from the server

    I am also interested in other ideas and approaches

提交回复
热议问题