Unable to grab complete Handlebars template from Javascript - javascript

I am using Handlebars and AJAX to re-render template on every AJAX response. However, nothing is happening, neither template is rendered nor any error message is shown by browser. On little debugging, I found out that javascript is not grabbing complete hbs template.
Here is my Handlebars template:
<!--Template-->
<script id="careers-template" type="text/x-handlebars-template">
<ul>
{{#each careers_list}}
<li class="mt-list-item">
<div class="list-icon-container">
<button data-toggle="tooltip"
title="Add to Favorites"><i
class="fav-btn ion ion-ios-heart-outline font-red-intense"></i>
</button>
</div>
<div class="list-item-content">
<h3 class="uppercase">
{{this}}
</h3>
</div>
</li>
{{/each}}
</ul>
</script>
Here is console output of source:
<ul> </ul>
Here is my AJAX call:
$.ajax({
url: '/dashboard/careers/get_careers_list',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({category: category})
}).done(function (data) {
var container = $("#career-detail-list");
var source = $("#careers-template").html();
var template = Handlebars.compile(source);
var list = template({careers_list: data});
console.log(source);
container.html(list);
});
The AJAX return an array of strings.
Can anyone please help why javascript is not grabbing complete hbs template??

The problem is careers_list is empty.
Check if its this.careers_list instead of just careers_list
Also send the key in quotes
var list = template({'careers_list':data})

Related

Handlebar Each and JSON API call how do I get it to transfer the data from array response and put it on a handlebars modal

$("#searchMovieBtn").click(() => {
const movieSource = $("#movie-template").html();
const movieList = Handlebars.compile(movieSource);
const movieSearch = $("#addMovie").val();
console.log(movieSearch);
queryURL = `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${movieSearch}&page=1&include_adult=false`;
$.ajax({
url: queryURL,
method: "GET"
}).then(response => {
console.log(response);
const results = response.results;
const data = { movies: [] };
for (let i = 0; i < results.length; i++) {
const currentTitle = {
title: results[i].title,
release_date: results[i].release_date
};
data.movies.push(currentTitle);
}
console.log(data);
$("#placeholder").html(
movieList({
data: data
})
);
});
});
});
this is my function to call it
<div id="placeholder"></div>
<script type="text/x-handlebars-template" id="movie-template">
<ul class="list-group">
{{#each movies}}
{{#each this}}
<li class="list-group-item text-dark" id="MovieTitle">{{title}}
<span>
(<span id="MovieYear">{{release_date}}</span>)
<span>
<button class="btn btn-warning text-light btn-sm" id="addMovieBtn">Add to watchlist</button>
</span>
</span>
</li>
{{/each}}
{{/each}}
</ul>
</script>
And what it is going into!
I have been up all night and just cannot figure out what is going on with it! I swear I have looked up and down and still cannot find the right method to use it is driving me mad! Anyways thanks for the help ahead of time I am sure it was something very very simple that I looked over a lot.
There are a few errors in your solution.
First, you must understand the context object that you are passing to your template. It's shape looks like this:
{
data: {
movies: [
{
title: "Movie Title",
release_date: "Year"
}
]
}
}
Notice that the first key in the object is data. However, in your template, you have no reference to data, but try to access movies directly, effectively skipping a reference. Given this data, the first #each in your template would need to be updated to:
{{#each data.movies}}
Your second problem is your second #each in your template. This #each iterates over each property of each movie in the movies array. So when you reference a property like {{title}} within this block, the full path of your reference is something like data.movies[i].title.title. There is an extra '.title' there because you are not within the context of the movie, but of one of its properties (title in this case).
To fix this, simply remove the second #each.
I have created a fiddle for your reference.
As an additional note: I would avoid including static element IDs inside of a loop. It means you will have duplicate IDs in your output and that is not valid HTML.

AngularJS, get data from external source and push into array

I'm trying to call an external scrip that gets data from a database, so I can then populate a select dropdown. I've tried this so far, but I get a load of empty li elements. It is the right count of what there should be just nothing showing?
My controller
app.controller('agenciesController', function($scope, $http) {
var url = "/ajax/getAgencies.php";
$http.get(url).success( function(response) {
$scope.agencies = response;
$scope.agenciesArray = [];
angular.forEach(response, function(value, key){
$scope.agenciesArray.push(value);
})
console.log($scope.agenciesArray);
});
})
My HTML
<body ng-controller="Controller">
<div ng-controller="agenciesController">
<ul ng-repeat="agencyName in agencies">
<li>{{agenciesArray.agencyID}}</li>
</ul>
</div>
</body>
UPDATE -
This code is working but not returning only one response but all.
<div ng-controller="agenciesController">
<ul ng-repeat="agencyName in agenciesArray">
<li>{{agencyName}}</li>
</ul>
</div>
agenciesArray is an array. agenciesArray.agencyID will be undefined. that is why you are gettting empty li.
Do you intend to do this?
<ul ng-repeat="agency in agenciesArray">
<li>{{agency.agencyName}}</li>
</ul>
Try this
<ul ng-repeat="agencyName in agencies">
<li>{{agencyName.agencyID}}</li>
</ul>
Reason:Because agencyArray is nothing in the given context

unexplained undefined string displayed on my website. not sure how to get rid of it

I have a undefined string being displayed on my page and i have no idea why it is their besides the function that is probably causing it, i only know this from displaying allot of console errors to locate the problem.
I believe that Mustache is doing this somehow when i call on templates.
"
undefined
"
The question is how do i get rid of this undefined string being injected in my page. Any help would be much appreciated.
Code:Function that is being called that is somehow or reason displaying a undefined string in my div
getProjects: function(){
portfolio.topOfPage();
var request1 = $.ajax({
url: "js/projects.js",
dataType:'json',
cache: true,
}).then(function(response){
var data = response.projects;
var template = $('#projects_tmp').html();
var projects;
$.each(data, function(key,val){
console.log("Key: "+key+", Value: "+val);
projects += Mustache.to_html(template, val);
});
return projects;
});
My mustache template:
<script id="projects_tmp" type="text/template">
<div class='small-6 medium-3 large-2 columns left thumb {{{genre}}}' data-id='{{{id}}}'>
<div class='project'><figure><img src='{{{largePic}}}' alt='' />
<figcaption class='caption'><span>{{genre}}</span></figcaption class='caption'></figure></div>
</div>
</div>
</script>
Problem is your projects variable should have a default value of '', in your getProjects method when you are doing projects += it is adding undefined value which comes by default.
I see 3 </div> and just 2 <div> in your code posted above. Not sure if that might be the issue.

Read Json and update template from mustache

I have a Index.html file, where I am using container class.
I have another html file with which contains mustache variables.
Here is the code which I am using,
Lets say this is a.html.
<script id="filtersOptions" type="text/html">
<ul class="checkboxCommonContent">
{{#data}}
<li>
<div>
<input type="checkbox" id="checkbox-1-1" class="regular-checkbox"><label for="checkbox-1-1"></label><span class="lblText">{{brand_name}}</span>
</div>
</li>
{{/data}}
</ul>
I have a json file, where the brand information something like this,
{
"brands":[
{
"brand_name":"Adidas",
"available_products":30
}
]
}
Through Javascript I am featching the Json data and trying to udapete the mustache tempalte but getting error.
Featchng information from js
loadFileForFilters: function(){
$.getJSON('js/json/brand.json', {}, function(data, textStatus, jqXHr) {
console.log(data);
var f = $("#filtersOptions").html();
$.get('files/sort_and_filter_lb.html', function(template, textStatus, jqXhr) {
var template = Mustache.render(f, {data: data});
//$(".container").html(template);
});
});
}
container - Is in side index.html.
The sort_and_filter_lb.html file have following code
<script id="filtersOptions" type="text/html"><ul class="checkboxCommonContent"> {{#data}} <li> <div> <input type="checkbox" id="checkbox-1-1" class="regular-checkbox"><label for="checkbox-1-1"></label><span class="lblText">{{brand_name}}</span> </div> </li> {{/data}} </ul> </script>
Can some one please guide me. Why I am not getting the data in the main template.
Edit,
Browsed some documentations MUSTACHE MANUAL , and demonstrations A Simple Mustache Demo , along with re-reading Question , for introduction into Mustache.js .
At first glance , appear that json object at brand.json does not have data property to correspond to {{#data}} ; see http://mustache.github.io/mustache.5.html#Sections at template and hash of {{#repo}}.
Not certain about necessity of second ajax call, i.e., $.get() ? Existing #filtersOptions (f) html could be modified , to reduce ajax call to first , $.getJSON() ?
Above portions not directly addressed here , though ajax pieces re-arranged to process their respective return values within .then() callback .
Changed <script> element at sort_and_filter_lb.html file to <div> , for jsfiddle to process .
Note, Not previously tried Mustache.js
Try
v2
html
<script id="filtersOptions" type="text/html">
<ul class="checkboxCommonContent"> {{#data}}
<li> <div> <input type="checkbox"
id="checkbox-1-1"
class="regular-checkbox" /> <label
for="checkbox-1-1"> </label><span class="lblText">{{brand_name}}</span> </div>
</li> {{/data}}
</ul>
</script>
<div class="process">
<button>Process Template</button>
</div>
<div id="container"></div>
js
$(function () {
$(".process button").on("click", function () {
var f = $('#filtersOptions').html();
var _data = {
"brands": {
"data": [{
"brand_name": "Adidas"
}, {
"available_products": 30
}]
}
};
var file = String('<div id=filtersOptions type=text/html>'
+'<ul class=checkboxCommonContent> {{#data}} <li>'
+'<div>'
+'<input type=checkbox id=checkbox-1-1 class=regular-checkbox>'
+'<label for=checkbox-1-1></label>'
+'<span class=lblText>{{brand_name}}</span>'
+'</div> </li> {{/data}} </ul> </div>');
var request1 = $.post("/echo/json/", {
json: JSON.stringify(_data)
}, function (data, textStatus, jqxhr) {
return data.brands;
});
var request2 = $.post("/echo/html/", {
html: file
}, function (data, textStatus, jqxhr) {
return data
});
$.when(request1, request2)
.then(function (a, b) {
console.log(a[0], b[0]);
var html = Mustache.render(b[0] /* or , `f` */, a[0].brands);
$('#container').html(html);
})
});
});
jsfiddle http://jsfiddle.net/guest271314/uhf73/
Your code appears a little messed up but close. If you want to render a template using an external file and external data, try something like this:
$.getJSON('js/json/brand.json', {}, function(data) {
// on success, request template
$.get('files/sort_and_filter_lb.html', function(template_string) {
// when we have both template and data, render it
var output = Mustache.render(template_string, {data: data});
$(".container").html(output);
});
});

Template not working with JSON / Mustache.js

I am currently running into trouble with Mustache.js templates. Everything seems to be correct, and the template loads as HTML on the page. But it doesn't have access to the JSON data and I'm not quite sure why. Can anyone help out? Thanks in advance.
The Javascript that I am using is below.
query.find({
success: function(results){
var template = $("#newCurrItem").html();
var newContents = Mustache.to_html(template, results);
$("#curr-list").append(newContents);
},
error: function(error){
console.log("error");
}
});
This image shows the JSON format:
http://i.imgur.com/JrYrORk.png?1
And, here is the template:
<script id="newCurrItem" type="text/html">
{{#results}}
<!-- Template for new curriculum -->
<li id="curr-list-item">
<div id="curr-item">
<input type="checkbox" class="item-delete">
<label id="item-content" class="item-content">{{curr}}</label>
</div>
</li>
{{/results}}
</script>
Try structuring your JSON data more like this:
{ "results" : [
{
"curr": "curr_dbc",
"createdAt" : ...,
"updatedAt":...
}
]};

Categories