Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Iterative loop in jade isn't rendering data correctly

Iterative loop in jade isn't rendering data correctly

Problem

I've got a table in Jade that'll be dynamically generated through express (res.render('index', {classes: results})):

table
  tr
    th Title
    th School
    th Description
- if (classes.length) {
- classes.forEach(function(aClass) {
  tr
    td= aClass.title
    td= aClass.school
    td= aClass.desc
- });}

However, when I render it, the data comes out as one garbled mess. Looking at the HTML source reveals that the tag is before the content in classes. How can I solve this?

Problem courtesy of: SomeKittens

Solution

You've almost got it - jade is being finicky here. When creating an Iterative Loop, you need to make sure that your JavaScript is indented to the same level as your data:

table
  tr
    th Title
    th School
    th Description
  - if (classes.length) {
  - classes.forEach(function(aClass) {
  tr
    td= aClass.title
    td= aClass.school
    td= aClass.desc
  - });}

If this makes your inner coder cringe at the code style, I'm with you. However, that's the way it is. Alternatively, you could use jade's each (documented here)

table
  tr
    th Title
    th School
    th Description
  - if (classes.length) {
  each aClass in classes
    tr
      td= aClass.title
      td= aClass.school
      td= aClass.desc
  - }

Again, this looks a little wonky but is the jade way to iterate.

Solution courtesy of: SomeKittens

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Iterative loop in jade isn't rendering data correctly

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×