Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive iteration over an object in Jade template?

I have an object of mixed type properties - some strings, some arrays of strings, some objects containing arrays of strings - that can potentially go many levels deep.

I would like to iterate over all properties so that an object creates a div, an array creates a div, and a string property creates a span to contain the text.

{ "string" : "some text", "object" : { "array" : [ "text" ] } }

The above object would render as:

<span>some text</span>
<div>
  <div>
    <span>text</span>
  </div>
</div>

But usually much more complex structures. How should I go about accomplishing this is Jade?

like image 457
Tom Avatar asked Nov 13 '11 22:11

Tom


3 Answers

It's been a while since you asked, but mixin is your friend, I think. I haven't tried it out, but if mixins support recursion, this should work:

mixin parseObject(obj)
  div
    - each val, key in obj
      - if (typeof val === 'string')
        span #{val}
      - else if (typeof val === 'object')
        mixin parseObject(val)

Then in the body of your .jade file, call mixin parseObject(rootObject).

like image 173
mna Avatar answered Nov 03 '22 06:11

mna


Recursion seems to be suppported now. I have successfully used the function with a minor tweak; you need to use the mixin keyword when calling the function.

mixin parseObject(obj)
  div
    each val, key in obj
      if typeof val === 'string'
        span #{val}
      else if typeof val === 'object'
        mixin parseObject(val)
like image 7
Thijs Koerselman Avatar answered Nov 03 '22 05:11

Thijs Koerselman


In the modern version of Jade it's look like

mixin parseObject( obj )
  div
    each val in obj
      if typeof val === 'string'
        span= val
      else if typeof val === 'object'
        +parseObject( val )

Then in the body of your .jade file, call

+parseObject( rootObject )

like image 7
Sunrise Avatar answered Nov 03 '22 07:11

Sunrise