Include Assets Only If They Exist

前端 未结 5 1692
情歌与酒
情歌与酒 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:13

    To include an asset based on controller name

    <% controller_asset = controller.controller_name %>
    <%= stylesheet_link_tag controller_asset if YourApp::Application.assets.find_asset(controller_asset) %>
    

    To include an asset based on controller name and action name (was useful for me)

    <% action_asset = "#{controller.controller_name}/#{controller.action_name}" %>
    <%= stylesheet_link_tag action_asset if YourApp::Application.assets.find_asset(action_asset) %>
    

    And of course it'd be better not to leave this code as it is, but rather place it in a helper.

提交回复
热议问题