I'm trying to use Jade for a simple web app for html templating. I have JSON that looks like:
{
"responses": [
{
"fieldOne": 1,
"fieldTwo": 2,
"fieldThree": "Some string"
},
{
"fieldOne": 10,
"field2": 20,
"fieldFour": "Some other string"
}
]
}
I'm trying to loop over this responses list in Jade, and create a row in a table for each response. The looping seems to work fine, the issue is that some responses are missing fields, and I'd like to put a blank in that cell if the field is missing. I'm passing into Jade a map (from Spark) with only one entry, "responseData", which maps to the whole JSON object.
body
div
table
thead
tr
th Field One
th Field Two
th Field Three
th Field Four
tbody
each val in responseData.responses
tr
td
#{val.fieldOne}
td
#{val.fieldTwo}
td
#{val.fieldThree}
td
#{val.fieldFour}
This works right now if each response has all four fields. I'd like to replace these with if conditions checking that the field exists before it tries to read the value. Something like:
td
if val.fieldFour
#{val.fieldFour}
This returns 'inaccessible or unknown property fieldFour' if fieldFour doesn't exist. I'd like to know how to check if val has a specific property. I've tried following Jade tutorials, trying things like prepending things with locals
, using bracket notation, etc. but to no avail. I haven't found an example where this is done inside a loop, so that might be an issue.
I've looked at all the other stack overflow questions I can, so any help is appreciated! Thanks!
I've managed to get this working by swapping the hashes #
for an exclamation mark !
.
The difference between the two is the #
is escaped and the !
is raw data. You can see working examples of the difference here - http://naltatis.github.io/jade-syntax-docs/#escaping
Jade:
- responseData = { "responses": [{"fieldOne": 1,"fieldTwo": 2,"fieldThree": "Some string"},{"fieldOne": 10,"field2": 20,"fieldFour": "Some other string"}]}
table
thead
tr
th Field One
th Field Two
th Field Three
th Field Four
tbody
each val in responseData.responses
tr
td
if val.fieldOne
!{val.fieldOne}
td
if val.fieldTwo
!{val.fieldTwo}
td
if val.fieldThree
!{val.fieldThree}
td
if val.fieldFour
!{val.fieldFour}
I've got a working version here - http://codepen.io/AdamCCFC/pen/akrjVv