LoginSignup
22
32

More than 5 years have passed since last update.

PugのIncludeやMixinなど

Posted at

Includes

includeを使ってファイルの読み込みが可能。
共通ヘッダーなどに使うとよい。pugファイルだけでなく、PlainTextやMarkdownも読み込める。

//- index.pug
doctype html
html
  include includes/head.pug
  body
    h1 My Site
    p Welcome to my super lame site.
    include includes/foot.pug


//- includes/head.pug
head
  title My Site
  script(src='/javascripts/jquery.js')
  script(src='/javascripts/app.js')

//- includes/foot.pug
footer#footer
  p Copyright (c) foobar        

詳しくはこちら

Template Inheritance

blockextendsを使ったテンプレートの継承が可能。
レイアウトテンプレートをextendsを使って呼び出し、その下にblockを定義する。
再定義しなければ初期値として用意したものがレンダリングされる(サンプルコードでいうところのfoot)
また、block内でのincludeも可能である。

//- layout.pug
html
  head
    title My Site - #{title}
    block scripts
      script(src='/jquery.js')
  body
    block content
    block foot
      #footer
        p some footer content

//- page-a.pug
extends layout.pug

block scripts
  script(src='/jquery.js')
  script(src='/pets.js')

block content
  h1= title
  - var pets = ['cat', 'dog']
  each petName in pets
    include pet.pug

//- pet.pug
p= petName

オーバライドなども可能なので詳しくはこちら

Block append / prepend

テンプレートをオーバライドするだけでなく、アペンドやプリペンドも可能。

//- layout.pug
html
  head
    block head
      script(src='/vendor/jquery.js')
      script(src='/vendor/caustic.js')
  body
    block 

//- page.pug
extends layout.pug

block append head
  script(src='/vendor/three.js')
  script(src='/game.js')

Mixins

Mixinも作成可能。

//- Declaration
mixin list
  ul
    li foo
    li bar
    li baz
//- Use
+list
+list
mixin pet(name)
  li.pet= name
ul
  +pet('cat')
  +pet('dog')
  +pet('pig')

Mixin Blocks

MixinでBlockも使用可能。

mixin article(title)
  .article
    .article-wrapper
      h1= title
      if block
        block
      else
        p No content provided

+article('Hello world')

+article('Hello world')
  p This is my
  p Amazing article

もう少しサンプルを見たければこちら

22
32
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
22
32