LoginSignup
6
4

More than 5 years have passed since last update.

jadeで共通レイアウトを使いつつ、ページに個別のclassをつける。

Posted at

はじめに

ページごとに個別 class をつけて、その class で css や js の処理を分岐することが多々あります。
jadeを使っていると共通のテンプレートは利用できるのですが、html や body に個別 class をつけるのってどうすればいいんだろうと思ったのでそのメモです。

やり方

共通レイアウト

_defaultLayout.jade

doctype html
block init
    - var pageTitle = 'サンプルページ';
    - var htmlClass = '';

//- htmlにhtmlを付与する場合
html(lang='ja', prefix='og: http://ogp.me/ns#', class= htmlClass)
    head
        meta(charset='UTF-8')
        meta(http-equiv='X-UA-Compatible', content='IE=edge')
        meta(name='viewport',content='width=device-width, initial-scale=1')
        meta(name='description',content='')
        meta(name='author',content='')
        link(rel='icon',href='/favicon.ico')
        title= pageTitle
        link(type='text/css', rel='stylesheet', href='/css/style.css')
        block additional-css
        != '\n<!--[if lt IE 9]>\n\t\t\t'
            script(src='https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js')
        != '\n\t\t\t'
            script(src='https://oss.maxcdn.com/respond/1.4.2/respond.min.js')
        != '\n\t\t<![endif]-->\n'
        block afterhead
    body#top
        block main

そして、この共通テンプレートを呼び出すファイルを下記のように設定

index.jade

extends _defaultLayout

block append init
    //- ページタイトルの設定
    - pageTitle = 'インデックスページ';

    //- ページclassの設定
    //- このページに特定のclassを付与できる。
    - pageClass = 'indexPage';

block main
    h1 これでページにclassがつくよ。

その後、コンパイルすると見事 class が付与されてます。

index.html

<!DOCTYPE html>
<html lang="ja" prefix="og: http://ogp.me/ns#" class="indexPage">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="/favicon.ico">
        <title>インデックスページ</title>
        <link type="text/css" rel="stylesheet" href="/css/style.css">
        <!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
            <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body id="top">
        <h1>これでページにclassがつくよ。</h1>
    </body>
</html>

変数を block init に定義して append で変数の値を上書きし、それを共通テンプレートにはめるというやり方で無事できました。

6
4
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
6
4