LoginSignup
63
55

More than 5 years have passed since last update.

content_forの使い方(haml)

Last updated at Posted at 2014-06-19

railsdoc (http://railsdoc.com/references/content_for)の説明および例がとてもわかりにくかったので、自分なりに理解したことをメモ。

content_forとは?

  • ある画面でだけcssファイルやjsを呼びだしたい場合に、利用するメソッドです。平たくいうと、画面のコンテンツを追加実装する仕組み、でしょうか。

実装例

  • index.htmlのみでintro.css.scssというスタイルシートを呼び出したい場合は以下のように実装します。

layouts/application.html.haml

%html
  %head
    %meta{ charset: 'UTF-8' }
    %meta{ name: 'viewport', content: 'initial-scale=1.0, user-scalable=no' }    
    = stylesheet_link_tag    'application'
    = javascript_include_tag 'application'
    = yield :header  # コンテンツ名を:headerと定義します

views/index.html.haml (呼び出したい画面)の文頭

- content_for(:header) do
  = stylesheet_link_tag "intro"  # /assets/stylesheets/intro.css.scssを呼び出します
  • これを実行すると、- content_for(:header) do ~ end内部の処理がheadで追加で読み込まれます

実行結果

<html>
  <head>
    <meta charset='UTF-8'>
    <meta content='initial-scale=1.0, user-scalable=no' name='viewport'>
    <title>
      タイトル
    </title>
    <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" />
    <script src="/assets/application.js?body=1"></script>
    <meta content="authenticity_token" name="csrf-param" />

    <link href="/assets/intro.css?body=1" media="screen" rel="stylesheet" />
(以下略)
63
55
1

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
63
55