在 rails 资产管道中的 js.coffee 文件中使用 erb 时出错 [英] Error using erb in js.coffee files in the rails asset pipeline
问题描述
我有以下代码:
/assets/javascripts/home.js.coffee.erb
jQuery ->
addClickListeners = ->
$(document).on 'click', '#add-chord-link', addChord
$(document).on 'click', '#remove-chord-link', removeChord
addChord = (e) ->
e.preventDefault()
console.log("<%= asset_path('rails.png') %>")
console.log("<%= link_to 'Sign up now!', '#' %>")
console.log('addChord clicked')
$('#chord-choices').append('addedChord')
removeChord = (e) ->
e.preventDefault()
$('#chord-choices select').last().remove()
console.log('removeChord clicked')
addClickListeners()
console.log("<%=asset_path('rails.png') %>")
的控制台输出是 /assets/rails.png
,这是我所期望的.但是,每当我包含 console.log("<%= link_to 'Sign up now!', '#' %>")
时,我都会在页面加载时收到错误消息:p>
The console output for the console.log("<%= asset_path('rails.png') %>")
is /assets/rails.png
, which is what I expect. However, whenever I include console.log("<%= link_to 'Sign up now!', '#' %>")
I get an error when the page is loaded stating:
undefined method `link_to' for #<#<Class:0x007f9095960938>:0x007f9095b78ab8>
为什么这不起作用?
推荐答案
问题
原因是资产 pineline 背后的宝石 Sprockets 不依赖 Rails 来处理 erb.查看可用的本地助手 https://github.com/sstephenson/sprockets#invoking-ruby-with-erb
Rails 在 ActiveSupport 中为 Assets Pineline 添加了更多帮助程序,您可以使用它们.你可以在这里找到它们:http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html
Rails added some more helpers to Assets Pineline in ActiveSupport, they are all you can use. You can find them here: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html
link_to
是属于 ActionView 的助手,因此它不包含在 Assets Pineline 中.
link_to
is a helper belonging to ActionView, so it's not included in Assets Pineline.
有一些解决方案可以让您在 Assets Pineline 中使用 ActionView 助手:
There are some solutions to allow your using ActionView helpers within Assets Pineline:
https://github.com/sstephenson/sprockets/issues/218
如果您只需要相关链接或更多链接,则无需费心破解.使用纯文本或 Javascript 助手.够了.
If all you need is the link in question or a little bit more, no need the trouble to hack around. Use plain text or a Javascript helper. That's enough.
//plain text
"<a href='#'>Sign up</a>"
//JS helper
Link = {}
Link.sign_up = "<a href='#'>Sign up</a>"
Link.link_to = (url, anchor) ->
"<a href="#{url}">#{anchor}</a>"
console.log(Link.sign_up)
console.log(Link.link_to("#", "Sign up"))
这篇关于在 rails 资产管道中的 js.coffee 文件中使用 erb 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!