Search code examples
jsonpugharp

Harp Server, Jade and JSON Loop, Error: Cannot read property "length" of undefined


This is the nav.jade file

each link in data
h5.home-link: a(href="#{ url }")

This is my data.json file

{
      "links": [
        { "url": "index.html", "pg-title": "Home" },
        { "url": "Wooden_Wall_Panelling.html", "pg-title": "Wooden Wall Panelling" },
        { "url": "Wooden_Partitioning.html", "pg-title": "Wooden Partitioning" },
        { "url": "Wardrobe_MDF_Shutters.html", "pg-title": "Wardrobe MDF Shutters" },
        { "url": "MDF_Ceiling_Patterns.html", "pg-title": "MDF Ceiling Patterns" },
        { "url": "Wooden_Grills.html", "pg-title": "Wooden Grills" }
     ]
}

Error(while Jade tries to compile the file):

Cannot read property 'length' of undefined.

The error is pointed on the first line i.e each link in data.

What am I doing wrong here?

I am using Harp Server.


Solution

  • First, make sure it’s a _data.json file, with an underscore in front. Then, your nav.jade file should look like this:

    each link in public._data.links
      h5.home-link: a(href="#{ link.url }") #{ link["pg-title"] }
    

    If you change your pg-title to title in your _data.json file, you can also make the syntax a little cleaner:

    each link in public._data.links
      h5.home-link: a(href="#{ link.url }") #{ link.title }
    

    You can also drop the string interpolation if you want:

    each link in public._data.links
      h5.home-link: a(href=link.url)= link.title
    

    There’s also more about info about metadata in Harp here. If you’re debugging and want to see how all your metadata is available in Harp, you can be helpful to temporarily display the entire public _data object:

    pre: code= JSON.stringify(public._data, 0, 2)