collenjones
collenjones

Reputation: 530

Inline conditional in Jade?

I am passing an object, school, into my edit form and want to set one of these options as selected. School has a property focus such that for JavaScript school.focus = 1, for Python school.focus = 2, and for Ruby on Rails school.focus = 3)

How could I write an inline conditional to set one of these options as 'selected'?

//- Focus
div(data-role='fieldcontain')
  fieldset(data-role='controlgroup')
    label(for='focus') Focus
      select(name='focus')
        option(value='JavaScript') JavaScript
        option(value='Python') Python
        option(value='Ruby on Rails') Ruby on Rails

I have gotten this type of inline conditional to work when there is an assignment (value=):

//- School Name
    div(data-role='fieldcontain')
      fieldset(data-role='controlgroup')
        label(for='school_name') School Name
          input(id='school_name',type='text', value=(school ? '#{school.school_name}' :     ''),placeholder='School name here',name='school_name')

Upvotes: 0

Views: 2003

Answers (1)

Matt Ball
Matt Ball

Reputation: 360066

Fortunately for you, Jade is awesome and you don't need to use a ternary at all. KISS.

div
  fieldset
    label Focus
      select
        option(value='JavaScript', selected=(school.focus == 1)) JavaScript
        option(value='Python', selected=(school.focus == 2)) Python
        option(value='Ruby on Rails', selected=(school.focus == 3)) Ruby on Rails

So, if locals.school.focus is 2, then you'd end up with this markup:

<div>
  <fieldset>
    <label>Focus
      <select>
        <option value="JavaScript">JavaScript</option>
        <option value="Python" selected="selected">Python</option>
        <option value="Ruby on Rails">Ruby on Rails</option>
      </select>
    </label>
  </fieldset>
</div>

Demo @ http://jsfiddle.net/mattball/Razge/

I recommend refactoring slightly to separate the values and labels from the markup, so that you can have Jade iterate over them for you, but that's the general idea.


N.B. you can omit a label's for attribute entirely if the label is the parent of the element you want to label. In spec-speak, that's:

If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element's labeled control.

...all of which to say: in your case, that label's for attribute is superfluous and you can get rid of it.

Upvotes: 2

Related Questions