简体   繁体   English

如何使用rails代码/传递变量到.coffee javascript文件?

[英]How to use rails code / pass variables to a .coffee javascript file?

What would be the best way to pass values inside a .coffee script? 在.coffee脚本中传递值的最佳方法是什么? Renaming the file to .erb breaks my app so what are the alternatives? 将文件重命名为.erb会破坏我的应用程序,那么有哪些替代方案呢?

checkout this rails guide. 结帐这个rails指南。 this section : 2.3.3 JavaScript/CoffeeScript and ERB You can use rails code in .coffee-script file. 本节内容: 2.3.3 JavaScript / CoffeeScript和ERB您可以在.coffee-script文件中使用rails代码。 It's built-in feature. 它的内置功能。

2nd Edit___ 第2编辑__

If the file is in assets pipeline then you need to add .erb extension at end of coffee file so that the rails tag works otherwise there is no need to add .erb extension if you moves the file in views folder rails tag works there. 如果文件在资源管道中,那么你需要在咖啡文件的末尾添加.erb扩展名,这样rails标签就能正常工作,否则如果你在视图文件夹中移动文件,就不需要添加.erb扩展名。

You can either (1) move the file into your app/views directory (so it won't be in the asset pipeline), or (2) pass the information via query string. 您可以(1)将文件移动到app / views目录中(因此它不会在资产管道中),或者(2)通过查询字符串传递信息。

(1) app/views/users/script.js.coffee.erb (1)app / views / users / script.js.coffee.erb

var username = <%= @user.name %>

(2) I'm using this function (2)我正在使用这个功能

<%= link_to "User", user_path(@user, :username => @user.name) %>
...
var username = getParameterByName('username')

Untested but this is the general idea. 未经测试,但这是一般的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM