Rails - how to include Javascript files only on certain pages

前端 未结 2 1445
执笔经年
执笔经年 2021-02-06 03:09

I have a WYSIWYG editor that I have built into the site and customised. There are a lot of Javascript files that only need to be loaded on the pages with the WYSIWYG editor; cur

2条回答
  •  不知归路
    2021-02-06 03:45

    This is getting old now and we're in a Webpacker world with Rails 6, but if you want to keep things more simple in the old school Sprockets way, you might like the approach described below. Note that it really is per-view - other answers have good approaches for wider scope per-controller stuff.

    Have your main layout declare a 'content for' section. For example, in application.htm.erb:

    
    
      
        <%= csrf_meta_tags %>
        <%= csp_meta_tag %>
        ...etc...
    
        <%= content_for :head %>
    
      
      ...
    
    

    Here, :head is just a label and you can give it any name you want. You can have as many such declarations in your layout as you want, too. They're just Rails's way of letting views insert extra stuff into those bits of your outer layout. So - you use this from within individual views to add your JS file(s)

提交回复
热议问题