Creating Dynamic Classes in Jade/Pug
Asked Answered
C

2

14

I'm trying to add a dynamic class to a jade template. Like so:

- var obj = {a: 1, b: 2, c: 3};
- var len = Object.keys(obj).length;

.abc-#{len}

But the compiler is taking exception to this:

  > 4| .abc-#{len}
------------^

Unexpected token `interpolation` expected `text`, `interpolated-code`, `code`, `:`, `slash`, `newline` or `eos`

I've tried everything I could think of. Been scouring https://pugjs.org/language/interpolation.html. Could really use a hand.

Thanks.

Cristincristina answered 16/12, 2016 at 18:15 Comment(0)
A
28

You can do this:

div(class="abc-"+len)

attributes are interrupted automatically, more about attributes

Antilepton answered 16/12, 2016 at 18:21 Comment(1)
The class value can also be an array: div(class=['foo', 'bar', 'baz']Overfill
B
10

You can use ES6 template literals as well. E.g.

div(class=`static_${dynamic_variable}` 

In your case:

div(class=`abc-${len}`)

Have fun.

Bunnybunow answered 6/7, 2018 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.