Jade (node.js) - more than one class on an element?
Asked Answered
R

4

41

in jade one can write:

div.container

and it compiles into:

<div class="container"></div>

But what if you have several classes like:

<div class="span 4"><div>

I have written it like this:

div(class="span 4")

But I am thinking: Is there not a better way of doing it in jade?

Ramin answered 17/3, 2012 at 14:28 Comment(0)
M
94

From the documentation:

how about some classes?

div.user-details

renders <div class="user-details"></div>

multiple classes? and an id? sure:

div#foo.bar.baz

renders <div id="foo" class="bar baz"></div>

Mackey answered 17/3, 2012 at 14:33 Comment(3)
This does not work for me (2.0.4 version of pug). It first adds the classes and at the end it appends the id. div#foo.bar.baz will generate <div class="bar baz" id="foo"></div>.Vladamir
@Vladamir looks like that worked just fine to me. The order of attributes doesn’t matter, so it’s all the same.Mackey
You are correct. I was misled by the applied order of css.Vladamir
C
9

The following format

    div#MyBox.span12.blueButton.moveLeft

will create

    <div id="MyBox" class="span12 blueButton moveLeft"></div>
Congratulatory answered 18/9, 2013 at 6:8 Comment(0)
D
5

You don't have to specify div

#MyBox.span12.blueButton.moveLeft     

will apply the selected class and id on a div element :

Since div's are such a common choice of tag, it is the default if you omit the tag name: .content compiles to <div class="content"></div>

See the Pug (new name for Jade) documentation.

However you have to specify the tags of each and every other element you use with an id or class.

Ex.

body
  #page
    header.row
      h1= title
    .row
      p Express App
Disposed answered 15/2, 2014 at 19:37 Comment(0)
W
0

Note that you can combine the .classname syntax with the class attribute:

// Input:
.foo.bar(class="baz qux")

// Output:
<div class="foo bar baz qux"></div>

And the class attribute also supports arrays and objects for more advanced use cases.

From the Class Attributes section in the documentation (slightly modified for clarity):

The class attribute can be a string, like any normal attribute; but it can also be an array of class names, which is handy when generated from JavaScript.

Input:

- const classes = ['foo', 'bar', 'baz']

a(class=classes)

//- the class attribute may also be repeated to merge arrays
a.bang(class=classes class=['bing'])

Output:

<a class="foo bar baz"></a>
<a class="bang foo bar baz bing"></a>

It can also be an object which maps class names to true or false values. This is useful for applying conditional classes.

Input:

- const currentUrl = '/about'

a(class={active: currentUrl === '/'} href='/') Home
a(class={active: currentUrl === '/about'} href='/about') About

Output:

<a href="/">Home</a>
<a class="active" href="/about">About</a>
Worcestershire answered 21/1, 2021 at 7:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.