Pug: Conditional parent div without copying children

Viewed 282

We have something like this:

 .child
   a.child-2
     img(src)

if i want to add wrapper for this elements i do it like:

if something === true
  .parent
     .child
       a.child-2
         img(src)
else
     .child
       a.child-2
         img(src)

If there are a lot of children we have a problem of doubling and bad readability How do i write a condition for wrapper element alone wihout need to make else statement and copy every child in it?

1 Answers

This is a great use-case for a Pug mixin with a mixin block:

mixin conditionalWrapper(arg)
  if arg
    .parent
       block
  else
    block

The block declaration renders any children of the mixin. It can be used like this. If the argument is true, the contents will be rendered within the .parent wrapper. If it's false, they'll be rendered without the wrapper.

- let something = true

+conditionalWrapper(something)
  .child
    a.child-2
     img(src)
Related