在用于资产管道的 javascript 中嵌入 erb 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8966048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Embedding erb code in javascript for asset pipeline
提问by Zubin
In my rails 3.1.3 app, I'd like to insert some ERB code in my javascript file but it's not being parsed for some reason:
在我的 rails 3.1.3 应用程序中,我想在我的 javascript 文件中插入一些 ERB 代码,但由于某种原因它没有被解析:
# app/assets/javascripts/application.js
//= require_tree ./shared
# app/assets/javascripts/shared/shared.js.erb
MM.loading = '<img src="<%= asset_path("icons/ajax-loader.gif") >">';
Gets rendered like this in /application.js
:
在 中像这样呈现/application.js
:
MM.loading = '<img src=" asset_path("icons/ajax-loader.gif") >">';
I can't see any extra steps in the rails guides - is there something I'm missing? Btw I'm using haml for the view files, and also tried the above with .js.haml
, enclosing in #{...}
.
我在导轨指南中看不到任何额外的步骤 - 有什么我遗漏的吗?顺便说一下我使用HAML的视图文件,并且也尝试了上面.js.haml
,在封闭#{...}
。
回答by Richard Hulse
You have a syntax error in your code. This:
您的代码中有语法错误。这:
MM.loading = '<img src="<%= asset_path("icons/ajax-loader.gif") >">';
should be this:
应该是这样的:
MM.loading = '<img src="<%= asset_path("icons/ajax-loader.gif") %>">';
You were missing the closing erb tag for the helper block of code.
您缺少帮助程序代码块的结束 erb 标记。
回答by Richard Hulse
Add a .erb extension to your application.js and it should work.
向您的 application.js 添加一个 .erb 扩展名,它应该可以工作。
The content of required files gets included first, then processed according to the extensions on the manifest.
首先包含所需文件的内容,然后根据清单上的扩展名进行处理。