如何在Rails 4中将javascript_include_tag与js.erb文件一起使用?

Abr*_*ram 9 javascript ruby ruby-on-rails ruby-on-rails-4

以下是我的看法:

<%= javascript_include_tag "social_sharing.erb" %>
Run Code Online (Sandbox Code Playgroud)

然后我有:assets/javascripts/social_sharing.erb.js其中包括一些ERB标签,如<%= post.id %>......

第一个问题是我看到此错误消息:

`Asset filtered out and will not be served: add `Rails.application.config.assets.precompile += %w( social_sharing.erb.js )` to `config/initializers/assets.rb` and restart your server
Run Code Online (Sandbox Code Playgroud)

如果我遵循这些指示,然后我将获得js文件,但没有评估任何ERB标记,所以我仍然<%= post.id %>在链接的js文件中看到.

trv*_*frd 11

应该命名该文件assets/javascripts/social_sharing.js.erb(最后使用.erb),否则Rails资产管道将不知道如何处理它并将其作为纯JavaScript进行提供.尽管.js是可选的,但include标签应该是读取<%= javascript_include_tag "social_sharing.js" %>而不是..erb

资产文件夹中的所有内容都将通过资产管道进行处理,并且可以使用资产助手标记轻松获取.

但是,javascript_include_tag资产管道用于真正的静态资产,只能预编译一次,然后为每个相关请求提供相同的文件.如果您尝试包含动态内容,例如<%= post.id %>因请求而异,您可能希望将.js.erb文件移动到views目录中的某个位置并将其呈现为部分,类似于第一个答案.这个问题:

<script>
    render partial: '[somewhere]/social_sharing', post: @post
</script>
Run Code Online (Sandbox Code Playgroud)

该文件也需要重命名_social_sharing.js.erb.