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":...
}
]};
Related
I am trying to use mustache and jQuery to import a JSON and create a html template.
I have followed tutorials to get to this point, but nothing shows in the browser and there are no error messages.
HTML
div id="repeatcontent"/div
Script: I import mustache, greate the template script and then use javascript to import the JSON.
<script src=mustache.min.js></script>
<script id="tutorials" type="text/template">
{{#a_tutorials}}
<p>{{title}}<p/>
{{/a_tutorials}}
</script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('audacity_tutorials.JSON', function(data) {
var template1 = $('#tutorials').html();
var html = Mustache.to_html(template1, data);
$('#repeatcontent').html(html);
});
});
</script>
JSON
{
"A_tutorials" : [
{
"Title" : "Binary",
},
{
"Title" : "Clipping",
}
]
}
There are no error messages, and the screen is completely blank. I have also used console.log to try and figure it out but it returns all the data I ask it for.
Your mistakes are:
A_tutorials in json file while you use a_tutorials in js
Title in json file while you use title
your json file is incorrect. For instance this line
"Title" : "Binary",
must be changed with:
"Title" : "Binary"
You may test json online by yourself.
Mustache is case sensitive.
// $.getJSON('z.json', function(data) {
var data = {
"A_tutorials" : [
{
"Title" : "Binary"
},
{
"Title" : "Clipping"
}
]
};
var template1 = $('#tutorials').html();
var html = Mustache.to_html(template1, data);
$('#repeatcontent').html(html);
// });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script id="tutorials" type="text/template">
{{#A_tutorials}}
<p>{{Title}}<p/>
{{/A_tutorials}}
</script>
<div id="repeatcontent"></div>
I'm working on a Meteor application that should fulfil a datalist with some data stored in a JSON file as part of a process. However, I didn't succeed in importing its data to a template. So I was wondering how I could solve this.
I have stored the JSON file into panel/skills.json, and it looks like this basically:
{"skills":[
{"value":".NET Compact Framework"},
{"value":".NET Framework"},
{"value":".NET para Web"}
]}
And this is how the HTML file looks like:
<div class="required">
<input type="text" class="form-control" list="tags">
<datalist class="form-control" id="tags" name="tags">
{{#each skills}}
<option value={{value}}></option>
{{/each}}
</datalist>
</div>
Is there any way of getting the JSON file into a .js archive, and load it using helpers? Thank you :)
I didnt try but this will work.
load json file using require
store values to reactiveVar
return from helper
Example:
var json = require('panel/skills.json');
Template.myTemplate.onCreated(function() {
this.skills = new ReactiveVar(json);
});
Template.myTemplate.helpers({
skills: function (){
return Template.instance().skills.get();
}
});
Use Can create a method in you Meteor.methods
meteor.methods({
getSkills: function (){
var Skills = JSON.parse(Assets.getText("parse/skills.json"));
return Skills.skills;
}
})
And now invoke this method in your template
Template.skills.helpers({
skills: function (){
Meteor.call('getSkills', function(err, result){
return result;
}
}
})
I did not test yet, but I alread use something like these.
Stuck with javascipt's knockout library.
So, I want to implement simple forum. I have javascript file with two ajax requests, for topics and for posts. And I have html template.
function dealModel() {
var self = this;
self.board = ko.observableArray([]);
var res = [];
$.getJSON("http://someaddress/threads", function(data) {
$.each(data, function(i, thread) {
var js = jQuery.parseJSON(thread);
js.posts = ko.observableArray([]);
var postres = []
$.getJSON("http://someadress/posts/" + js.id, function(postdata) {
$.each(postdata, function(idx, post){
var jspost = jQuery.parseJSON(post);
postres.push(jspost);
})
})
js.posts(postres);
res.push(js);
})
self.board(res);
})
}
$(document).ready(function(){
ko.applyBindings(new dealModel());
});
var testdata = [{text : "text 1"} , {text : "text2"}]
This is my js code. It perfectly works with topics, but when I put my posts, my observable array "posts" already empty.
For test I created test array "testdata" (below), and pass in my observable array. And, javascript work perfectly.
Here is my template
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script type="text/javascript" src="ajaxknockout.js"></script>
</head>
<body>
<div class='board'>
<div class='threads' data-bind="foreach: board">
<p data-bind="text: title"></p>
<div class= "posts" data-bind="foreach: $data.posts">
<p data-bind="text: text"> </p>
</div>
</div>
</div>
</body>>
</html>
So, I think something bad with my posts JSON.
Here it is.
["{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 1\",\"id\": \"4\"}", "{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 2\",\"id\": \"5\"}", "{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 3\",\"id\": \"6\"}"]
SO, I have a question. Whats wrong with my code? Why knockout understand my testdata, but completly reject production data?
That's because this part of your first json request:
js.posts(postres);
executes ahead of callback from your second json request where you are pulling posts. You have to change that so the posts array is populated before doing js.posts(postres);, e.g like so:
$.getJSON("http://someadress/posts/" + js.id, function(postdata) {
$.each(postdata, function(idx, post){
var jspost = jQuery.parseJSON(post);
postres.push(jspost);
})
js.posts(postres);
})
Currently I have a json file that populates information to my chart. An example of this chart can be found here: http://marmelab.com/ArchitectureTree/. I also have a panel to the right which is meant to display the information of one of the charts node's when clicked. However I don't know how to do this.
Say if I had in my json array:
{
"name": "Blogs",
"url": "blogs.my-media-website.com/*",
"dependsOn": ["Wordpress MU"],
"technos": ["PHP", "Wordpress"],
"host": { "Amazon": ["?"] }
},
I would click on 'Blogs' in the chart and the 'url', 'dependsOn' etc would then be displayed in the panel. I'm sure this function uses AngularJS to do this. Can someone point me in the right direction on how to do this?
On click of Blogs call below function :
In your controller, try adding this function.
$scope.onClickOfBlogs = function(){
$http.get('Your_JSON_file_Path_here').success(function(response){
$scope.jsonObject= response;
}).error(function() {
console.log('error occured while getting JSON file');
});
};
in your Panel HTML : -
<div id ="info">
<span>URL : {{jsonObject.url}} </span>
<span>Name : {{jsonObject.name}} </span>
<ul>
Depends on :
<li ng-repeat = "depends in jsonObject.dependsOn"> <!-- to iterate on array you need ng-repeat -->
{{depends}}
</li>
</ul>
</div>
you will get the data from json file into your html panel.Hope this helps.
**
** : http://plnkr.co/edit/dbJ0bhHhvASffJU9liY6?p=preview
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);
});
});