LoginSignup
11
6

More than 5 years have passed since last update.

pugでmixinに複数のblockを渡す方法

Last updated at Posted at 2017-04-14

正確には、blockではないのだけど。

結論

mixin.pug
mixin Contents()
  block
  ul.Contents
    li.item.item0
      +content0
    li.item.item1
      +content1
    li.item.item2
      +content2
index.pug
html
  head
  body
    +Contents
      mixin content0
        span.index0
          |コンテンツ0
      mixin content1
        span.index1
          |コンテンツ1
      mixin content2
        span.index2
          |コンテンツ2
exported.html
<html>
  <head></head>
  <body>
    <ul class="Contents">
      <li class="item item0">
        <span class="index0">コンテンツ0</span>
      </li>
      <li class="item item1">
        <span class="index1">コンテンツ1</span>
      </li>
      <li class="item item2">
        <span class="index2">コンテンツ2</span>
      </li>
    </ul>
  </body>
</html>

仕組み

pugでは、mixin呼び出しの時に1つインデントを付けてコードを書くと、その内容をmixin内のblockの部分に入れてくれる。
そこで、そのblockの中に、mixin渡すことで、呼び出されたmixin内で参照ができるようになる。

使いどころ

この例のように「3つのリストを表示する」ことが決まっているのにその内容が呼び出し箇所によって異なる場合に必要になる。例えばTabで切り替えるタイプのパネルだ。3画面分のHTMLを渡さなければいけないが、その枠組はmixin側に任せたいときなどに重宝する。

関連ページ

Allow multiple blocks to be defined inside mixins and includes · Issue #631 · pugjs/pug

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