简体   繁体   English

如何在Rails帮助器的内插ERB字符串中包含coffeescript变量?

[英]How can I include a coffeescript variable in an interpolated ERB string in a rails helper?

I would like to include this coffeescript variable ( chordCount ) in the ERB below, but when it runs it has an error because it is trying to interpret chordCount as a ruby variable. 我想在下面的ERB中包含该coffeescript变量( chordCount ),但是当它运行时会出错,因为它试图将chordCount解释为ruby变量。 How can I use it in the ERB? 如何在ERB中使用它?

app/views/static_pages/add_chord.js.coffee (below) is reached via a remote: true link. 通过remote: true链接访问app/views/static_pages/add_chord.js.coffee (如下)。 It works perfectly with the one exception mentioned above (eg if I replace the variable with "4" then it works fine, but with the variable it throws an error). 它与上面提到的一个异常完美地配合使用(例如,如果我将变量替换为“ 4”,则它可以正常工作,但是对于变量,它将引发错误)。

chordCount = $('.chordSearchForm').find('.chordSearchFieldRow').length

# define the html for the row to add
rowToAdd = "<div class='row chordSearchFieldRow'>" +
    "<div class='large-8 small-12 columns'>" +
    '<%= collection_select :chords, :chord_#{chordCount}, Chord.order("name ASC"), :id, :name, {}, { :multiple => false, class: "chordSearchField", id: "chord_#{chordCount}_search_field" } %>' +
    "</div>" +
    "</div>"

Thanks! 谢谢!

Firstly, you don't want to be writing html like this. 首先,您不想像这样编写html。 Use the tag helpers: 使用标签助手:

http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag

Secondly, for storing variables for use in javascript, it's best to set it in a data attribute. 其次,要存储用于javascript的变量,最好在data属性中进行设置。

An example might look like this: 一个例子可能看起来像这样:

content_tag(:p, data: { chord_count: chordCount })

which would make it available in your js by 这将使它在您的js中可用

$("p").data("chord_count")

if your using jquery. 如果您使用的是jQuery。

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

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