Rails:访问 CoffeeScript 或 JavaScript 资产文件中的控制器实例变量 [英] Rails: access controller instance variable in CoffeeScript or JavaScript asset file

查看:18
本文介绍了Rails:访问 CoffeeScript 或 JavaScript 资产文件中的控制器实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 3.1 中,无法使用诸如 <%= @foo %> 之类的语法访问资产 js.erb 或 coffee.erb 文件中的控制器实例变量,其中 @foo 在控制器中设置.那么问题是将控制器变量传递给 CoffeeScript 或 JavaScript 资产的最佳方法是什么.

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 controller. So then the question is what are the best ways for passing controller variables to CoffeeScript or JavaScript assets.

这个问题在论坛上以多种复杂的形式被问过,但我再次提出这个问题的目的是有一个地方可以将所有建议聚集在一起,并且提供的代码简单易读.另请注意,我特指资产而不是查看响应文件.

This question has kind of been asked in multiple convoluted forms on the forum, but my point in asking it again is to have a place where all recommendations are gathered together, and the code supplied is simple and readable. Also note that I'm specifically referring to assets and not view response files.

推荐答案

我过去做过的几种方法

将数据放入隐藏字段,访问js/coffee中的数据

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")

另一种选择:将数据加载到erb中的js数据结构中,从js/coffee访问

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

<% content_for(:head) do %>
    <script>
    window.App = window.App || {};
    window.App.Data = window.App.Data || {};
    window.App.Data.fooList = [
        <% @list.each do |foo| %>
            <%= foo.to_json %>,
        <% end %>
    ];
    </script>
<% end %>


# coffee
for foo in window.App.Data.fooList
    console.log "#{foo.id}, #{foo.first_name} #{foo.last_name}"

我不喜欢像这样在 erb 中从 ruby​​ 构建 javascript 数据,关于它的一些东西只是感觉不对 - 虽然它可以是有效的

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

另一种选择:进行ajax调用并从服务器按需获取数据

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

这篇关于Rails:访问 CoffeeScript 或 JavaScript 资产文件中的控制器实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆