如何在 PUG 中的包含文件中使用块?

How to use a block inside an included file in PUG?

我想做这样的事情

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

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

block content
    include ./layout2.pug
        block article1
            something something....
        block article2
            something something....

文章 1 和文章 2 在 layout2.pug 文件中

目前,不允许在 Pug 中使用多个块,请参阅 issue

但是,使用 mixin block 我们可以模拟多个块。 例如:

index.pug

//- important to use `var`, not `let` or `const`
- var blocks = blocks || {}

mixin block(name)
  -
    if (this.block && !this.block.length)
      blocks[name] = this.block
    else if (!!blocks[name]) blocks[name]()

//- define your custom block with name `article1` 
+block('article1')
  p something something 1 ...

//- define your custom block with name `article2`
+block('article2')
  p something something 2 ...

//- use the `include` after block definitions
include article

article.pug

h2 Articles
ul
  li
    //- output block with name `article1`
    +block('article1')
  li
    //- output block with name `article2`
    +block('article2')

生成HTML:

<h2>Articles</h2>
<ul>
  <li>
    <p>something something 1 ...</p>
  </li>
  <li>
    <p>something something 2 ...</p>
  </li>
</ul>