user1964638 user1964638 - 4 months ago 17x
HTML Question

How can i give the first element of list a class in jade?

I want to assign the first element within a list to a class like this

<input type="button" value="Top View" class="button selected-view">
<input type="button" value="Front View" class="button">
<input type="button" value="Side View" class="button">
<input type="button" value="Back View" class="button">
<input type="button" value="Perspective" class="button">

I can do it with a for loop like this

- var cameraChoice = ["Top View", "Front View", "Side View", "Back View", "Perspective"]
- for (i = 0; i < cameraChoice.length; i++)
if i === 0
input.button(type="button" class=" selected-view" value=cameraChoice[i])
input.button(type="button" value=cameraChoice[i])

but I wanted to know if there was a better way to do this. Something more along the lines of

each view in ["Top View", "Front View", "Side View", "Back View", "Perspective"]
input(type="button" class="button" value=view)

I'm just starting out with jade and I have tried to search for an answer but I haven't had any luck so far.


Solution 1: Your second approach is almost complete when looking for a quick solution. Just add the reference to the index of your array to your each statement. Furthermore you may use short conditional syntax:

each view,index in ["Top View", "Front View", "Side View", "Back View", "Perspective"]
  - var className = (index == 0) ? 'button selected-view' : 'button'
  input(type="button", class=className, value=view)

Solution 2: In a real world application your controlling code probably knows about currently active (selected) views, so the decision if an additional class attribute is applied to a specific button might depend on state contained in (JS) objects. Wherever this is created and resides, your code might later look like a bit different. Guess the following JS object holding information about available "perspective" views:

var views = { 
  'top': { 
    label: 'Top View', 
    selected: true
  'front': {
    label: 'Front View', 
    selected: false
  'side': {
    label: 'Side View', 
    selected: false


Then, you can also iterate over JS objects using the each statement within your jade file:

each view, index in views
  - var className = (view.selected) ? 'selected-view' : ''
  input(type="button", class='button', class=className, value=view.label)

Note that this time I used the attribute class twice. It illustrates an alternative way of applying multiple class attributes when using jade (personally I don't like it very much and prefer pre-built class name strings).

I hope this helps you a bit and at least answered your question. However, this is just one of several possible ways depending on your frontend/backend architecture.