how to iterate over an array of objects in handlebars - javascript

I have an array of objects that i have received from my web API, and i am using handlebars to create a template and iterate over these objects. However i am unsure on how i iterate over my array of objects.
JS:
$(document).ready(function(){
$.get("/api/CaseStudies/top", function (data) {
var caseStudies = [];
for (var i = 0, caseStudie; (caseStudie = data[i]); ++i) {
caseStudies.push(caseStudie);
}
//console.log(caseStudies);
renderTemplate(caseStudies);
});
function renderTemplate(caseStudies) {
var template = $('#test').html();
var templateScript = Handlebars.compile(template);
var html = templateScript(caseStudies);
$("#output").append(html);
}
});
HTML:
<script id="test" type="text/x-handlebars-template">
<div>
{{#each caseStudies}}
The title is {{Title}}And my name is{{Name}}<br />
{{/each}}
</div>
</script>
<div id="output"></div>
The array of objects i receive from my api looks like this:

Related

How to make javascript variables unique inside an asp.net core foreach?

I've something like the following in a razor page:
#foreach (var item in list)
{
<h3 id="time-#item.id"></h3> <!--The id is unique because of the addition of the list item's ID-->
<script type="text/javascript">
let currentDateTime-#item.id = new Date(Date.now());
$('#time-#item.id').html(currentDateTime-#item.id) // Item.id displays like text and doesn't apply to the variable itself.
function getdone-#item.id(){ // Functions too
}
</script>
}
I need to make those variables/function/IDs unique for each item of the list.
Wrap item.id in parentheses: #(item.id)
#foreach (var item in list)
{
<h3 id="time-#item.id"></h3>
<script type="text/javascript">
let currentDateTime-#(item.id) = new Date(Date.now());
$('#time-#(item.id)').html(currentDateTime-#(item.id));
function getdone-#(item.id)(){
}
</script>
}
Result:
https://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/

how to get class name of all tags of json using jquery

I have a JSON data and i want to list all attributes of class name inside divs and inner divs and tags.
Sample JSON DATA :
[
{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}
]
I have used children() but it is not taking inner class name, output i got is
main-header dark-bg row space-9 hide-md using the below code by taking json data in a variable
if($(t).children().length > 0){
console.log($(t).children().length);
//OUTPUT SHOWING 2
}
To achieve this you can use some relatively straightforward recursion to traverse down the DOM tree within the HTML string, something like this:
var data = [{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}]
function buildClassArray($el, arr) {
arr = arr || [];
$el.each(function() {
arr.push($(this).prop('class'));
$(this).children().each(function() {
buildClassArray($(this), arr);
})
});
return arr;
}
var classes = buildClassArray($(data[0].Field1));
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that if you want multiple classes on a single element to appear within their own entity in the array, simply split() the class string before you push it to the array:
var data = [{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}]
function buildClassArray($el, arr) {
arr = arr || [];
$el.each(function() {
arr.push(...$(this).prop('class').split(' '));
$(this).children().each(function() {
buildClassArray($(this), arr);
})
});
return arr;
}
var $el = $(data[0].Field1);
var classes = buildClassArray($el);
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Output key from array?

How can I output the peoples names below? e.g. Martin and Tabitha?
people:
- martin:
job: Developer
skills:
- python
- perl
- pascal
- tabitha:
job: Developer
skills:
- lisp
- fortran
- erlang
Here's the loop:
{{#each people}}
{{ this }}
{{/each}}
I've found the answer to be:
{{#each people}}
{{#key}}: {{this}}
{{/each}}
You can create a block helper list to iterate over people and use the current index as a private variable to obtain the name which is the first key in the object: Object.keys(context[i])[0].
Code:
var people = [{"martin": {"job": "Developer","skills": ["python","perl","pascal"]}}, {"tabitha": {"job": "Developer","skills": ["lisp","fortran","erlang"]}}];
// Register list helper
Handlebars.registerHelper('list', function (context, options) {
var out = '<ul>',
data;
if (options.data) {
data = Handlebars.createFrame(options.data);
}
for (var i = 0, l = context.length; i < l; i++) {
if (data) {
data.index = Object.keys(context[i])[0];
}
out += '<li>' + options.fn(context[i], {
data: data
}) + '</li>';
}
out += '</ul>';
return out;
});
// The main template
var main = Handlebars.compile($('#main').html());
// Register the list partial that 'main' uses
Handlebars.registerPartial('list', $('#list').html());
// Render the list
$('#output').html(main({
people: people
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script id="list" type="x-handlebars-template">
{{#list people}}
{{#index}}
{{/list}}
</script>
<script id="main" type="x-handlebars-template">
{{> list}}
</script>
<div id="output"></div>
Note: I have converted the yaml to an array for the code example.

Javascript Pushing Objects to Array

I'm unable to push objects to an array and i can't figure out why. At the moment, the result (records) repeats the last instance of the each loop.
JSFiddle
HTML
<div data-provider="prv1"></div>
<div data-rating="rtn1"></div>
<div data-price="prc1"></div>
<div data-provider="prv2"></div>
<div data-rating="rtn2"></div>
<div data-price="prc2"></div>
<div data-provider="prv3"></div>
<div data-rating="rtn3"></div>
<div data-price="prc3"></div>
<div data-provider="prv4"></div>
<div data-rating="rtn4"></div>
<div data-price="prc4"></div>
Javascript (w/ jQuery)
(function(){
var sort = $(".sort select");
var provider = $("[data-provider]");
var rating = $("[data-rating]");
var price = $("[data-price]");
var records = [];
var record = {};
$(provider).each(function(index, value){
record.provider = $(provider).eq(index).data("provider");
record.rating = $(rating).eq(index).data("rating");
record.price = $(price).eq(index).data("price");
records[index] = record;
});
})();
In your loop you set each index to be equal to record. Since the scope of record is the anonymous function, it will be the same object for each index.
What you want is for the scope to be the function provided to .each
Like this fiddle
$(provider).each(function(index, value){
var record = {};
...
});

How to render nested collections in Meteor?

Summary:
Child categories nested inside of Parent Categories are not getting rendered in a Meteor template.
Details:
Consider a data model for 'Category' as such:
// Model Schema
Category {
idCategory : 20, (id of the category itself)
idCategoryParent : 0, (idCategory of our parent category)
defaultLabel : "Movies" (our label)
}
There are parent categories and child categories. Parent categories have an idCategoryParent property value of 0. Child categories store the idCategory of their parents as their idCategoryParent property. I'm trying to loop through a collection of these Categories and render them in the following way:
<b>Movies</b> // parent category is in bold
<ul> // child categories are rendered as an unordered list
<li>Horror</li>
<li>Comedy</li>
<li>Action</li>
<li>Drama</li>
</ul>
<b>Music</b>
<ul>
<li>Rock</li>
<li>Classical</li>
<li>Ambient</li>
</ul>
However, this is what I actually get:
<b>Movies</b>
<ul> // empty...
</ul>
<b>Music</b>
<ul>
</ul>
Source Code:
// How we get the 'categories_parents' data
Template.content.categories_parents = function (){
/*
* Get all parent categories (categories with an idCategoryParent of 0)
*/
var parents = Categories.find({idCategoryParent:0});
var pCount = parents.count();
for (var i = 0; i < pCount; i++){
var pId = parents.db_objects[i]['idCategory'];
/*
* Get all child categories of the parent (categories with
* an idCategoryParent equal to value of parent category's idCategory).
*/
var children = Categories.find({idCategoryParent:pId});
var cCount = children.count();
/*
* Assign the child categories array as a property of the parent category
* so that we can access it easily in the template #each expression
*/
parents.db_objects[i]['children'] = children;
}
return parents;
}
// This is our template
<template name="content">
<h1>Categories</h1>
{{#each categories_parents}}
<b>{{defaultLabel}}</b><br />
<ul>
{{#each children}}
<li>{{defaultLabel}}</li>
{{/each}}
</ul>
{{/each}}
</template>
Other template configurations I have tried in troubleshooting:
{{#each children}}
<li>A Child Exists Here</li> // Even this never rendered... no children?
{{/each}}
Any clues as to why this is happening would be appreciated.
Your model is kind of iffy... Consider
{name:"Category name", parent:"_id of parent category"}
Okay, that's a lot simpler. To create a category.
var moviesId = Categories.insert({name:"Movies"});
Categories.insert({name:"Horror",parent:moviesId});
That was easy enough. Now, to render in a way that {{#each}} works:
Template.categories.categories = function(parent) {
if (parent) {
return Categories.find({parent:parent}).fetch();
} else {
return Categories.find({parent:{$exists:false}});
}
}
You might be seeing where this is going...
<template name="categories">
{{#each categories}}
<ul>{{name}}
{{#each categories _id}}
<li>{{name}}</li>
{{/each}}
</ul>
{{/each}}
</template>
Now I'm not sure if the {{#each}} block helper can take a function argument when it calls another helper. If it doesn't...
Template.categories.categories = function() {
return Categories.find({parent:{$exists:false}}).map(function(parentCategory) {
return _.extend(parentCategory,
{children:Categories.find({parent:parentCategory._id}).fetch()});
});
}
That's a real doozy. It returns parent categories with a new "children" list property, that contains all the children categories. Now you can do:
<template name="categories">
{{#each categories}}
<ul>{{name}}
{{#each children}}
<li>{{name}}</li>
{{/each}}
</ul>
{{/each}}
</template>
Clever, eh?
I don't know about db_objects, when I try and access that property on a cursor (which is what find() returns), it's null.
You could fetch the items that matches your query instead, and then do your iteration:
Template.content.categories_parents = function (){
var parents = Categories.find({idCategoryParent:0}).fetch(); // Returns an array.
for (var i = 0; i < parents.length; i++){
var pId = parents[i]['idCategory'];
var children = Categories.find({idCategoryParent:pId});
// No need for array here, cursor is fine.
parents.db_objects[i]['children'] = children;
}
return parents;
}
I'm new at this myself, so maybe there's a more efficient way of doing it, but I don't know it currently.
Update after Eric's comment.
The js file looks like this:
Categories = new Meteor.Collection("categories");
if (Meteor.isClient) {
Template.categories.categories = function () {
var parents = Categories.find({idCategoryParent:0}).fetch();
for (var i = 0; i < parents.length; i += 1) {
var pId = parents[i]['idCategory'];
var children = Categories.find({idCategoryParent:pId});
parents[i]['children'] = children;
}
return parents;
};
}
if (Meteor.isServer) {
Meteor.startup(function () {
Categories.remove({});
var data = [
{idCategoryParent: 0, idCategory: 1, label: "Movies"},
{idCategoryParent: 1, idCategory: 0, label: "Science Fiction"},
{idCategoryParent: 1, idCategory: 0, label: "Drama"},
{idCategoryParent: 0, idCategory: 2, label: "Music"},
{idCategoryParent: 2, idCategory: 0, label: "Jazz"},
{idCategoryParent: 2, idCategory: 0, label: "Piano"}
];
for (var i = 0; i < data.length; i += 1) {
Categories.insert(data[i]);
}
});
}
The html file looks like this:
<head>
<title>nested_template</title>
</head>
<body>
{{> categories}}
</body>
<template name="categories">
<h1>Categories</h1>
{{#each categories}}
<b>{{label}}</b>
<ul>
{{#each children}}
<li>{{label}}</li>
{{/each}}
</ul>
{{/each}}
</template>
It works just fine for me.
Solved.
My solution was to remove the {{#each}} logic from the template and replace it with a single handlebars helper expression, and pass back the needed html all at once. The html is generated from data in the cursor of the Categories collection.
Not so sure about having all this html in my logic though -- is this bad design? If so I'll defer to a better answer.
// This is the new template
<template name="content">
<h1>Categories</h1>
{{listCategories}}
</template>
// Handlebars helper
Handlebars.registerHelper('listCategories', function() {
var parents = Categories.find({idCategoryParent:0});
var countParents = parents.count();
var string = '';
// iterate over each parent category
for(m = 0; m < countParents; m++){
// Get the parents category id
var pId = parents.db_objects[m].idCategory;
var children = Categories.find({idCategoryParent:pId});
var count = children.count();
/*
* Build the Parent Category html
* Example: <b>Movies</b><ul>
*/
string = string + '<b>' + parents.db_objects[m].defaultLabel + '</b><ul>';
// iterate over each child category
for(var i = 0; i < count; i++){
/*
* Build the child category html
* Example: <li>Horror</li>
*/
string = string + '<li>' + children.db_objects[i]['defaultLabel'] + '</li>';
}
// Close up the unordered list
string = string + '</ul>';
}
// Return the string as raw html
return new Handlebars.SafeString(string);
});
// Rendered out the result correctly like so:
<b>Movies</b>
<ul>
<li>Horror</li>
<li>Comedy</li>
<li>Action</li>
<li>Drama</li>
</ul>
<b>Music</b>
<ul>
<li>Rock</li>
<li>Classical</li>
<li>Ambient</li>
</ul>

Categories