variable in class name jade
Asked Answered
E

5

38

I can't set a variable name in a class in jade:

.flag_#{ session.locale } #{ session.locale }

I have:

<div class="flag_" >en</div>

And I'd like to have

<div class="flag_en" >en</div>

Thanks

Elamite answered 2/12, 2012 at 11:33 Comment(0)
P
78

Try this (have not tested):

div(class="flag_#{ session.locale }") session.locale
Preordain answered 2/12, 2012 at 12:24 Comment(2)
Note that this also works if you have classes already in the Jade, like so: .flag(class="flag_#{session.locale}") session.locale => <div class="flag flag_en_GB">en_GB</div>Privative
Worked like a charmRemainder
I
16

As for [email protected] works this way:

div(class="flag_" + session.locale) session.locale
Inverter answered 19/4, 2016 at 14:19 Comment(1)
check the version you are using - @karaxuna's solution doesn't work anymore on pugBard
S
3

Here's another approach:

mixin formButton(text, type, extra_classes)
    - var default_classes = 'btn btn-primary'
    if extra_classes
        - var classes = default_classes + ' ' + extra_classes
    else
        - var classes = default_classes

    if type
        button(class=classes type=type) !{text}
    else
        button(class=classes type="submit") !{text}


Example 1:

Usage:

+formButton('Text')

Result:

<button type="text" class="btn btn-primary" type="submit">Text</button>


Example 2:

Usage:

+formButton('Text', 'button')

Result:

<button type="text" class="btn btn-primary" type="button">Text</button>


Example 3:

Usage:

+formButton('Text', 'button', 'extra-class')

Result:

<button type="text" class="btn btn-primary extra-class" type="button">Text</button>
Sew answered 13/6, 2015 at 20:47 Comment(0)
R
2

You can also use conditional statements to do this like

  if liked == true
    span.like.active
  else
    span.like
Revolutionist answered 18/4, 2015 at 3:6 Comment(0)
E
0

You can also use a template literal:

- const session = { locale: 'en' }
div(class=`flag_${session.locale}`) #{session.locale}

//- Just to show more options:

div(class=`flag_${session.locale}`)= session.locale
div(class=`flag_${session.locale}`) Current language is #{session.locale}
div(class=`flag_${session.locale}`)= `Current language is ${session.locale}`

Output (using Pug 2.0.4):

<div class="flag_en">en</div>
<div class="flag_en">en</div>
<div class="flag_en">Current language is en</div>
<div class="flag_en">Current language is en</div>
Episiotomy answered 21/1, 2021 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.