How to interpolate a string containing pug code within a pug file?

Viewed 288

I need to interpolate a string containing some pug formatted code within a pug file.

What I have tested:

- var text = "i.home.icon"

div= text
div !{text}
div #{text}
div ${${text}}
div {{text}}
div {text}
div \#{text}
div \{text}
div ${text}
div
    #{text}

What I want :

<div><i class="home icon"><i></div>
1 Answers

You could do this with a mixin. Here is a codepen that shows it working in a live example.

mixin tagCreator(def)
  - var tagArray = def.split('.');
  - var tag= tagArray[0];
  - tagArray.shift();
  - var classes = tagArray.join(' ');
  |<#{tag} class='#{classes}'>
  if block
    block
  |</#{tag}>

+tagCreator('one')
+tagCreator('two.three.four') Two

The code above creates this HTML:

<one class=""></one>
<two class="three four">Two</two>

A quick explanation of what it does, line by line:

  1. Splits the period-delimited string into an array
  2. Stores the tag name separately
  3. Removes the first element in the array
  4. Joins the rest of the array into a space-delimited string suitable for class="" output
  5. Use a pipe delimiter to output the plain text tag with classes
  6. Output any content added to the tag, if it exists
  7. Close the tag, again using plain text
Related