如何创建pugjs组件?

问题描述

是否有可能创建 pugjs 组件,我可以在其中调用该组件,例如 x-button Sign In

组件看起来像这样

button(class="py-3 px-8 rounded-lg inline-flex justify-center items-center font-semibold text-base leading-6 tracking-wide") #{text}

类似于这个概念Laravel component

解决方法

这就是 Pug mixins 的用途:

// declare the mixin
mixin x-button
  button.py-3.px-8.rounded-lg.inline-flex.justify-center.items-center.font-semibold.text-base.leading-6.tracking-wide
    if block
      block

// use the mixin
+x-button Sign In
,

组件的 Pug 等价物是 template inheritanceincludes。包含适用于您的用例:

//- includes/button.pug
button(class="py-3 px-8 rounded-lg inline-flex justify-center items-center font-semibold text-base leading-6 tracking-wide") #{text}
//- some-page.pug
//- index.pug
doctype html
html
  head
  body
    - var text = 'some-button-text'
    include includes/button.pug