LoginSignup
23
25

More than 5 years have passed since last update.

Railsで特定のaction毎にcssやjavascriptを読み込ませる方法

Last updated at Posted at 2015-04-02

いろんなところでいろんな方法が紹介されてるのですけど、どれもしっくり来ずでして、自分なりの方法を考案してみました。

下記が僕のポリシーです

  • Controllerにはその処理を書きたくない
  • Helperとか作りたくない
  • というかviews配下だけで済ませたい
  • (bodyにかいてもうまくいくっちゃうまくいくが)stylesheet_link_tag, javascript_include_tagをheadタグの間に納めたい

1. application.html.hamlのheadタグに下記を挿入

%head
  :
  = render :partial => "#{controller.controller_name}/head_#{action_name}" rescue nil
  :

2. app/views/{contorller名}/head{action名}.html.hamlを作成する

特定のjsやcssを読み込ませたいcontroller/action専用にheadに読み込ませるpartialを作る

たとえばUsersControllerのshow時だけに読み込ませたいものがあるのであれば`app/views/users/_head_show.html.haml ファイルを作成します。

3. あとは読み込みたいCSSやJSを書くだけ。

= javascript_include_tag 'hoge', ..
:
= stylesheet_link_tag    'application', ..
:

このやり方のメリットとして、js,css以外にもOGP設定などもできます。

23
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
25