渲染部分资产

我正在使用Ruby on Rails 3.1,我想知道如何在javascript资产中渲染部分内容。

我的目标是:

# in /app/assets/javascript/cart.js.coffee.erb $('a.add_sth').click -> $('.random_container').append('') 

这会导致NoMethodError:

 undefined method `render' for #<#:0x007fc5474cd470> 

如果我写而不是它工作正常,顺便说一句。

我认为问题是资产管道独立于默认的ActionView,这就是为什么render()在那里是未知的。 无论如何,有没有办法让部分内容呈现?

坏消息,渲染不可用看看: GitHub上的同样问题

请记住,资产用于静态数据,如CSS,JS或不会动态更改其内容的图像,因此可以更好地缓存和/或导出到CDN。

由于允许您使用ruby代码运行ERB,因此它应始终返回相同的值(因为它仅在编译资产时才会执行)。

这就是为什么我猜渲染在资产内部不可用(尽管它可以正确地用于渲染静态数据)。

这里简单的解决方案: 将您的JS文件移动到视图 ,在那里您将能够使用任何视图助手。

这对我有用。 (适用于HAML)

 = Haml::Engine.new(File.read(File.join(Rails.root, 'app/views/xxxxx','_form.html.haml'))).render(Object.new, :hello => "Hello World") 

并且,需要在文件开头添加依赖项以进行更新,例如:在这种情况下,需要将依赖文件放在资产中。

 //= depend_on xxxxx/_form.html.haml 

在轨道4.2

我发现这篇文章https://github.com/sstephenson/sprockets/issues/90 ,建议使用<%require_asset'path / to / file'%>

这对我有用。

我有类似的问题,所以我写了这个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应用程序上测试过它

事实上,它对我有用。 你需要这样做:

 = render 'way/to/partial' 

其中’way / to / partial’是现有资产文件夹下的相对路径。 有线的是,在路径中,您需要省略资产下的第一级文件夹。