这个是可以在 ERB 里面运行,如果是在 CoffeScript 里面该如何获取 Asset Pipeline 的图片地址呢?
$.fn.raty.defaults.starOff = <%= asset_path('something.png') %>
CoffeeScript 也可以写成 erb 的。把文件名从 foo.coffee 改成 foo.coffee.erb 就可以了。
#1 楼 @billy 谢谢。最终还是把那部分 JS 代码放到了 View ERB 里面去。怎么弄都觉得别扭。唉。先凑和。
@rocknrollhacker 是有些别扭,但要拿到 asset 地址必须通过 Rails helper。我也是不太喜欢 js 代码和后端混在一起。
还有一个办法其实也可行,会比较干净。
首先,你在需要做评级的 div 加一个 data attribute,比如 data-image,这个可以在 Rails 的 view 里面正常写,引用 asset_path
<div class="rating" data-image="#{asset_path('something.png')}">
然后,你自己写一个 plugin 的补充函数,比如这样
$.fn.raty.defaults.getImage = -> $('.rating').data('image')
最后,在设置图片时,直接调用这个函数
$.fn.raty.defaults.starOff = $.fn.raty.defaults.getImage()
这个就是 Unobtrusive Javascript 的写法了,分离比较干净。
2.3.3 JavaScript/CoffeeScript and ERB If you add an erb extension to a JavaScript asset, making it something such as application.js.erb, you can then use the asset_path helper in your JavaScript code: $('#logo').attr({ src: "<%= asset_path('logo.png') %>" }); This writes the path to the particular asset being referenced. Similarly, you can use the asset_path helper in CoffeeScript files with erb extension (e.g., application.js.coffee.erb): $('#logo').attr src: "<%= asset_path('logo.png') %>"
2.3.3 JavaScript/CoffeeScript and ERB
If you add an erb extension to a JavaScript asset, making it something such as application.js.erb, you can then use the asset_path helper in your JavaScript code:
$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });
This writes the path to the particular asset being referenced.
Similarly, you can use the asset_path helper in CoffeeScript files with erb extension (e.g., application.js.coffee.erb):
$('#logo').attr src: "<%= asset_path('logo.png') %>"
http://guides.rubyonrails.org/asset_pipeline.html#javascript-coffeescript-and-erb
#3 楼 @billy 赞!喜欢这个,确实是不喜欢在 coffee 里面在写 erb 的语法啊
#3 楼 @billy 这个方法真好,我怎么没有想到呢。看来还是要多学习多思考。