Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use javascript_include_tag with js.erb file in Rails 4?

Here is what I have in my view:

<%= javascript_include_tag "social_sharing.erb" %>

Then I have: assets/javascripts/social_sharing.erb.js which includes some ERB tags like <%= post.id %> ...

The first problem is I see this error message:

`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

If I follow those directions, I then get the js file served, but none of the ERB tags have been evaluated, so I still see <%= post.id %> in the linked js file.

like image 916
Abram Avatar asked Aug 25 '15 18:08

Abram


2 Answers

The file should be named assets/javascripts/social_sharing.js.erb (with .erb on the end), otherwise the Rails asset pipeline won't know to process it and will serve it up as if it were plain JavaScript. The include tag should read <%= javascript_include_tag "social_sharing.js" %> rather than .erb, although the .js is optional.

Everything in the assets folder will get processed through the asset pipeline and can be easily pulled in with asset helper tags.

HOWEVER, javascript_include_tag and the asset pipeline are for truly static assets that will only be precompiled once and then the same file served with every relevant request. If you're trying to include dynamic content such as <%= post.id %> that will vary from request to request, you will probably want to move the .js.erb file to somewhere in the views directory and render it as a partial, similar to the first answer for this question:

<script>
    render partial: '[somewhere]/social_sharing', post: @post
</script>

The file will need to be renamed _social_sharing.js.erb as well.

like image 154
trvrfrd Avatar answered Oct 06 '22 00:10

trvrfrd


I'm not sure this is the answer, but what you're doing with your asset pipeline vis a vis the javascript looks unusual.

To include the js in your assets precompile add this line in your /config/initalizers/assets.rb file.

Rails.application.config.assets.precompile += %w( social_sharing.js )  

I think once you include this file in your asset pipeline compilation you do not need to use the javascript_include_tag at all.

If you try this, please let me if you still have the error and or the rendering problem.

like image 36
Elvn Avatar answered Oct 05 '22 23:10

Elvn