In json2html, if I define an element in the template that doesn't exist in the JSON, I want to "display: none;" or perhaps better, just exclude the line in some way.
Example Template:
{"tag":"div","children":[
{"tag":"div","html":"First Name: ${first_name}"},
{"tag":"div","html":"Middle Name: ${middle_name}"},
{"tag":"div","html":"Last Name: ${last_name}"}
]}
Result:
First Name: John
Middle Name:
Last Name: Doe
If a middle name doesn't exist in the json, I don't want it to have a <div>
entry for the middle name, but instead skip that line.
What I'd like:
First Name: John
Last Name: Doe
One way to do this is:
Let the divs have ids/classes and I would suggest you to change the template layout in this format:
{"tag":"div","class":"container","children":[
{"tag":"div","class":"field","children":[
{"tag":"span", "html":"First Name:"},
{"tag":"span","html":"${first_name}"}
]
},
{"tag":"div","class":"field","children":[
{"tag":"span", "html":"Middle Name:"},
{"tag":"span","html":"${middle_name}"}
]
},
{"tag":"div","class":"field","children":[
{"tag":"span", "html":"Last Name:"},
{"tag":"span","html":"${last_name}"}
]
}
]}
After that gets processed, you can write a small code(jquery) like this:
$(".container div").each(function(){
var childs = $(this).children();
if($(childs[1]).is(":empty")){
$(this).hide();
}
});
I think it should work.
Hope it helps