我有类似的问题,所以我写了这个render
方法,可以在资产内部使用来渲染ERB部分模板:
# in lib/my_app/erb_helpers.rb
module MyApp
module ERBHelpers
class << self
def render(partial_path, binding)
dir_name, _, partial_name = partial_path.rpartition(File::SEPARATOR)
file_name = "_#{partial_name}.html.erb"
Erubis::Eruby.new(File.read(File.join(Rails.root, 'app', 'views', dir_name, file_name)).gsub("'", %q(\\\'))).result(binding)
end
end
end
end
然后我在coffeescript文件中使用它,如下所示:
# in app/assets/javascripts/notifications.coffee
MyApp.notifications.templates =
notice: '<%= ::MyApp::ERBHelpers.render 'application/notifications/notice', content: "%content%" %>'
alert: '<%= ::MyApp::ERBHelpers.render 'application/notifications/alert', content: "%content%" %>'
MyApp.notifications.create_elem = (type, content) -> MyApp.notifications.templates[type].replace('%content%', content)
PS:我在 Rails 5.0 应用上测试过