Include Assets Only If They Exist

前端 未结 5 1693
情歌与酒
情歌与酒 2021-02-19 07:41

In our current rails app, we are following certain patterns for including assets such as scripts and stylesheets.

For instance, one such pattern is (code inside the layo

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 08:12

    Simple ViewHelpers

    This is what I use myself. Add this to your ApplicationHelper:

    module ApplicationHelper
      def controller_stylesheet(opts = { media: :all })
        if Rails.application.assets.find_asset("#{params[:controller]}.css")
          stylesheet_link_tag(params[:controller], opts)
        end
      end
    
      def controller_javascript(opts = {})
        if Rails.application.assets.find_asset("#{params[:controller]}.js")
          javascript_include_tag(params[:controller], opts)
        end
      end
    end
    

    and use them like this in your application.html.haml:

    = controller_stylesheet
    = controller_javascript
    

    Note: This works with all .js, .coffee, .css, .scss even though it just says .css and .js

提交回复
热议问题