Skip to content

Instantly share code, notes, and snippets.

@mrgcohen
Last active December 13, 2015 20:18
Show Gist options
  • Select an option

  • Save mrgcohen/4968543 to your computer and use it in GitHub Desktop.

Select an option

Save mrgcohen/4968543 to your computer and use it in GitHub Desktop.
Javascript Load data into region. Pass in selector to load data to, data object. Will loop through data and place all the data into the locations based on the level and class. So you can easily template info
{
"person":{
"firstname":"Mike",
"lastname":"lovely",
"favs":{
"animal":"cat",
"activity":"cycling"
}
},
"comment":"i'm so tired"
}
<div class="info">
<div class="person_firstname"></div>
<div class="person_lastname"></div>
<div class="comment"></div>
<div class="person_favs_animal"></div>
<div class="person_favs_activity"></div>
</div>
function loadWith( selector,data,prefix ) {
var self = this;
prefix = prefix || "";
if (typeof data == "object") {
for (var key in data) {
console.debug(key,data[key]);
$(selector).find("."+(prefix?prefix+"_":"")+key).html(data[key]);
if (typeof data[key] == "object" && !(data[key] instanceof Array)) {
return self.loadWith(selector, data[key],(prefix?prefix+"_":"")+key);
}
}
} else {
$(selector).find("."+(prefix?prefix+"_":"")+key).html(data);
}
};
// data = data.json evaluated
// this will work based on current code
loadWith(".info",data);
// meta code
// or loop through a bunch and populate each
var friends = [data,data,data,data];
var i = 0;
for(var person in friends){
loadWith(".info"+i,person);
i++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment