Dynamic tag names in Pug

Published on in Pug

Last updated on

Use string interpolation at the beginning of a line, e.g. #{myVariable}.

Example:

- const tag = 'article'

#{tag}
#{tag}.foo
#{tag}(class="foo")
#{tag}.foo(class="bar")
#{tag}(class="foo").bar

// Output:
<article></article>
<article class="foo"></article>
<article class="foo"></article>
<article class="foo bar"></article>
<article class="foo bar"></article>

Works even inside tag interpolation:

- const tag = 'em'

p Bacon #[#{tag}.foo ipsum]!

// Output:
<p>Bacon <em class="foo">ipsum</em>!</p>

Dynamic tag names allow you to use fancy, probably invalid tag names. Like these:

#{':foo'} bar
#{'^'} baz

// Output:
<:foo>bar</:foo>
<^>baz</^>

// Compare with:

:foo bar
// Error: unknown filter ":foo"

^ baz
// Error: unexpected text "^ baz"

Not sure why you would want that though!

Read more about interpolations in Pug