这是我的观点:
<%= javascript_include_tag "social_sharing.erb" %>
然后我有: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
如果我按照这些说明进行操作,我就会得到 js 文件,但是没有评估任何 ERB 标签,所以我仍然看到 <%= post.id %>
在链接的 js 文件中。
最佳答案
文件应命名为 assets/javascripts/social_sharing.js.erb
(最后是 .erb),否则 Rails Assets 管道将不知道如何处理它并将它作为纯 JavaScript 提供。包含标签应显示为 <%= javascript_include_tag "social_sharing.js" %>
而不是 .erb
, 尽管 the .js is optional .
Assets 文件夹中的所有内容都将通过 asset pipeline 进行处理可以很容易地用 asset helper tags 拉进来.
但是,javascript_include_tag
Assets 管道用于真正的静态 Assets ,这些 Assets 只会被预编译一次,然后为每个相关请求提供相同的文件。如果您尝试包含动态内容,例如 <%= post.id %>
这会因请求而异,您可能希望将 .js.erb 文件移动到 View 目录中的某个位置并将其呈现为部分文件,类似于 this question 的第一个答案。 :
<script>
render partial: '[somewhere]/social_sharing', post: @post
</script>
文件需要重命名_social_sharing.js.erb
关于javascript - 如何在 Rails 4 中将 javascript_include_tag 与 js.erb 文件一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211252/