简体   繁体   English

帕格递归混合

[英]Recursive mixin in Pug

We use Pug to produce a style guide, and have a mixin to generate a header and description for reusable elements. 我们使用Pug生成样式指南,并使用mixin生成可重复使用元素的标题和描述。 A simplified example is this: 一个简化的示例是这样的:

mixin sgitem(name)
    if !isnested
        - isnested = true
        h3=name
        block
    else
        block
    - isnested = false

That means that if I write this: 这就是说,如果我这样写:

+sgitem('Foo')
    include partial with sgitem
+sgitem('Baz')
    div Example here

, the nested item should just return the block and not the name. ,则嵌套项应仅返回代码块而不是名称。 Well, that works, but not if there's a second or third nested sgitem: 好吧,那行得通,但是如果有第二个或第三个嵌套的sgitem,则不会:

+sgitem('Foo')
    include partial with sgitem
    include partial with sgitem
+sgitem('Baz')
    div Example here

That will generate this: 这将生成以下内容:

<h3>Foo</h3>
<div>Nested example</div>
<h3>Nested title</h3>
<div>Nested example</div>
<h3>Baz</h3>
<div>Example here</div>

, while I would like this: ,而我想这样:

<h3>Foo</h3>
<div>Nested example</div>
<div>Nested example</div>
<h3>Baz</h3>
<div>Example here</div>

It probably is an issue not with Pug per se, but with setting variables and so on. 这可能不是Pug本身的问题,而是设置变量等的问题。 So how can a mixin correctly know if it is nested or not? 那么,mixin如何正确知道它是否嵌套?

I feel like what you're trying to do is overly complicated. 我觉得您想要做的事情过于复杂。 Could you not just create something like the following? 您是否可以仅创建以下内容?

mixin sgitem(title, description)
  if title
    h3=title
  if description
    div=description

Then call the mixins: 然后调用mixins:

+sgitem('Foo', 'Nested example')
+sgitem('', 'Nested example')
+sgitem('Baz', 'Example here')

Which will render into: 它将呈现为:

<h3>Foo</h3>
<div>Nested example</div>
<div>Nested example</div>
<h3>Baz</h3>
<div>Example here</div>

We ended up splitting the mixin from its content, and including each of that content when needed. 我们最终将mixin从其内容中分离出来,并在需要时包括了每个内容。

Partial file A:
li List item example here

and

Page with atoms:
+sgmixin('A list item', 'Bla bla')
    include atoms/A


Page with molecules:
+sgmixin('A list', 'Bla bla')
    ul
        include atoms/A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM