如何在rails helper中的插值ERB字符串中包含coffeescript变量?

时间:2014-01-13 00:10:37

标签: javascript ruby-on-rails ruby coffeescript erb

我想在下面的ERB中包含这个coffeescript变量(chordCount),但是当它运行时它有一个错误,因为它试图将chordCount解释为ruby变量。我如何在ERB中使用它?

通过app/views/static_pages/add_chord.js.coffee链接访问

remote: true(下方)。它完全适用于上面提到的一个例外(例如,如果我用“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>"

谢谢!

1 个答案:

答案 0 :(得分:0)

首先,你不想写这样的HTML。使用标签助手:

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

其次,为了存储用于javascript的变量,最好将其设置在数据属性中。

示例可能如下所示:

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

可以通过

在你的js中使用它
$("p").data("chord_count")

如果你使用jquery。