Recursive mixin in Pug

Home / Uncategorized / Recursive mixin in Pug

Question:
We use Pug to produce a style guide, and have a mixin to generate a header and description for reusable elements. 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(‘Foo’)
include partial with sgitem
include partial with sgitem
+sgitem(‘Baz’)
div Example here

That will generate this:

Foo

Nested example

Nested title

Nested example

Baz

Example here

, while I would like this:

Foo

Nested example
Nested example

Baz

Example here

It probably is an issue not with Pug per se, but with setting variables and so on. So how can a mixin correctly know if it is nested or not?


Answer:

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *