How to render mustache template locally - javascript

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>

Related

Django, syntax for insering Javascript to template

I would like to embed Bokeh plot in Django template using Json output.
http://docs.bokeh.org/en/latest/docs/user_guide/embed.html#json-items
Json output is ready for query in database. Plot should be rendered to div with specific ID.
Documentation says to use Json output in template with following code function:
item = JSON.parse(item_text);
Bokeh.embed.embed_item(item);
Please advise the correct syntax for use in template:
<div id="title"></div>
<script>
function(response) { return item = JSON.parse( {{plot_json}} ); }
function(item) { Bokeh.embed.embed_item(item); }
</script>
View file:
def home(request):
plot_json = Price_Charts.objects.using('llweb').values('timeframe_1h').filter(symbol_pair='ETH')
context = {
'plot_json': plot_json
}
return render(request, "home.html", context)
I don't know much about Bokeh, but I know that you need to ensure that the JSON object is read correctly in the Django template as JavaScript and not auto-escaped. Give autoescape off a try along with the Bokeh 'then' syntax.
<div id="title"></div>
<script>
fetch('/plot')
.then(function(response) {
{% autoescape off %}
return item = JSON.parse( {{plot_json}} );
{% autoescape on %}
})
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
Maybe this simplified jinja2 example can help you (tested on Bokeh v1.0.4). Run it as:
python myapp.py
The file and directory structure:
myapp
|
+---myapp.py
+---templates
+---index.html
myapp.py
import io
import json
import jinja2
import numpy as np
from bokeh.plotting import figure, curdoc
from bokeh.embed import json_item
from bokeh.resources import CDN
plot = figure()
plot.line(np.arange(10), np.random.random(10))
curdoc().add_root(plot)
renderer = jinja2.Environment(loader = jinja2.FileSystemLoader(['templates']), trim_blocks = True)
html = renderer.get_template('index.html').render(resources = CDN.render(), item_json_object = json.dumps(json_item(plot)))
filename = 'json_items.html'
with io.open(filename, mode = 'w', encoding = 'utf-8') as f:
f.write(html)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{{ resources }}
</head>
<body>
<div id="myplot"></div>
<script>
Bokeh.embed.embed_item({{ item_json_object }}, "myplot");
</script>
</body>
</html>
It seems that the result of json.dumps(json_item(plot)) passed to the template is already a JSON object so you cannot use JSON.parse() on it. Or make sure you really pass a string object to this function.
The Bokeh documentation you refer to points to an example which is different from this one in the sense the plots data is loaded dynamically using JS fetch() method at page loading time in browser while here the plots data is attached to the page at template rendering time.

Comparing query string fields to display JSON using JS Render

I have a working JS Render template that pulls in a different JSON file based on the values of a query string. I am trying to figure out how to change the value of the JS Render element (id_1) based off of the query string field "source".
So if my url ends with "?market=ab&source=index", I want
"{{:id_1}}" to display "index_id_1" from the ab.JSON file.
HTML
<script type="text/x-jsrender" id="logoTempl">
<div id="cta-div">
Button
</div>
</script>
<div class="mainContainer">
</div>
JSON
[{"assets" : {
"field1" : "value",
"field2" : "value"
},
"ids" : {
"index": {
"id_1": "index_id_1",
"id_2": "index_id_2",
"id_3": "index_id_3"
},
"email": {
"id_1": "email_id_1",
"id_2": "email_id_2",
"id_3": "email_id_3"
}
}
}
]
JS
if (market == 'ab' && source == 'index') {
$.getJSON('data/ab.json', function(data) {
var logoField = logo.render(data);
var id1 = data[0].ids.index.id_1
$(".mainContainer").html(logoField);
$("{{:id_1}}").html(id1);
})
}
If I understand correctly you want the template to show the value ids[source].id_1.
You can pass in source as a helper, e.g.
...logo.render(data, {idgroup: source});
and then in the template, write:
{{:ids[~idgroup].id_1}}
or you can create a getId helper function, e.g.:
...logo.render(data, {getId: function(index) {
return data[index].ids[source];
}});
and then in the template, write:
{{:~getId(#index).id_1}}

jQuery autocomplete json file

Hi everyone i have an issue i want to make an autocomplete in jQuery and i have an json file in the same folder here is the code
var auto = $(function() {
$("#recherche").autocomplete({
source: "code.json",
minLength: 1,
})
});
and here is a sample of the json file :
{
"__type": "Featsee",
"feat": [
{
"id": {
"ID_THING": 1111
},
"properties": {
"CODTHING": "405136",
"TIONNEMENT": "VRAC"
}
}
]
}
the html code is the following :
<label for="tags" >Recherche lot : <input id="recherche" type="text" class="searchable" placeholder="rechercher ici"/></label>
the plugin is the following :
<script src="libs/jquery/js/jquery-2.1.1.min.js"></script>
<script src="libs/jquery/js/jquery-ui.js"></script>
the json file is correct but i want the autocomplete to be jus for CODTHING do you see how can i do that ??
and CODTHING is the code a want it to be the autocomplete
The JSON you provide to jQuery UI's autocomplete needs to be an array of objects with label and value properties or an array of strings.
http://api.jqueryui.com/autocomplete/#option-source
The rest of the answer I can only guess due to the brevity of the JSON you gave us.
If lots.json is just a plain JS file you can look through the `feat" array in your JSON data and return strings based on that.
(function($){
var lots = $.get('lots.json');
lots.done(function (results) {
var data = $.map(results.feat, function (lot) {
return lot.properties.CODTHING;
});
$("#recherche").autocomplete({
source: data
});
});
}(jQuery));
If lots.json is really a server side file that you can feed some data to and filter it there you can use a function like documented on this answer:
JQuery autocomplete source from another js function

Error rendering data with Javascript / KendoUI autocomplete - Object #<Object> has no method 'slice' - how to resolve?

I am following the Using Kendo UI with MVC4 WebAPI OData and EF article. After installing KendoUI and making sure all references are set, I type in three characters, and get the following error:
Uncaught TypeError: Object # has no method 'slice'
Root of the Problem
To save reading through the updates: Through debugging I found that the issue is that JS is expecting to parse an array, where it isn't available in the data - at the root. In the data hierarchy, it's one level in.
Original Problem
I cleaned up kendo.web.min.js and the error is occuring around line 3498:
success: function (n) {
var i = this,
r = i.options;
return i.trigger(wt, {
response: n,
type: "read"
}), n = i.reader.parse(n), i._handleCustomErrors(n) ? (i._dequeueRequest(), t) : (i._pristine = et(n) ? e.extend(!0, {}, n) : n.slice ? n.slice(0) : n, i._total = i.reader.total(n), i._aggregate && r.serverAggregates && (i._aggregateResult = i.reader.aggregates(n)), n = i._readData(n), i._pristineData = n.slice(0), i._data = i._observe(n), i._addRange(i._data), i._process(i._data), i._dequeueRequest(), t)
The Kendo UI widgets are loading just fine as well as the css:
<link href="~/Content/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.default.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/kendo/kendo.web.min.js"></script>
<script src="~/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="~/Scripts/appScripts.js"></script>
And I am seeing the same error both with using the Razor MVC helper/extension:
#(Html.Kendo().AutoComplete()
.Name("userAutoComplete") // specifies the "id" attribute of the widget
.DataTextField("USERNAME")
.DataSource(source =>
{
source.Read(read =>
{
read.Url("/api/user");
})
.ServerFiltering(true); // if true, the DataSource will not filter the data on the client
}
)
)
and through directly through JS:
/// <reference path="kendo/kendo.aspnetmvc.min.js" />
/// <reference path="kendo/kendo.core.min.js" />
/// <reference path="kendo/kendo.autocomplete.min.js" />
/// <reference path="kendo/kendo.web.min.js" />
$(document).ready(function () {
// load up KendoUI
// gets data from /api/user
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/user"
}
}
});
$("#userSearch").kendoAutoComplete({
dataSource: dataSource,
dataTextField: "USERNAME",
minLength: 3
});
$("#userSearch").on('input', function () {
console.log($("#userSearch").val());
});
}); // $(document).ready()
I'm sure this is something simple that I may be missing. I have tried both with the web and all js files.
Any assistance would be appreciated.
-- UPDATE --
The only real html missing from that content is the <input id="userAutoComplete" />
I created a brand new solution and a very simple view, based on one of the Kendo UI examples that gets JSON data from http://api.geonames.org, and getting the same error.
I thought that using the newest JS library (//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js may have been causing a problem so I tried the 1.7 lib. Same issue:
#using Kendo.Mvc.UI
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="#Url.Content("~/Content/kendo.common.min.css")">
<link rel="stylesheet" href="#Url.Content("~/Content/kendo.default.min.css")">
<link rel="stylesheet" href="#Url.Content("~/Content/kendo.dataviz.min.css")">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/kendo.web.min.js")"></script>
<script src="#Url.Content("~/Scripts/kendo.aspnetmvc.min.js")"></script>
<script src="#Url.Content("~/Scripts/kendo.dataviz.min.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#autoComplete").kendoAutoComplete({
minLength: 6,
dataTextField: "title",
filter: "contains",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "http://api.geonames.org/wikipediaSearchJSON",
data: {
q: function () {
return $("#autoComplete").data("kendoAutoComplete").value();
},
maxRows: 10,
username: "demo"
}
}
},
schema: {
data: "geonames"
}
}),
change: function () {
this.dataSource.read();
}
})
});
</script>
</head>
<body>
<div>
<input id="autoComplete"/>
</div>
</body>
</html>
-- UPDATE --
Using the code above, I went back and tried it again - it worked fine. After trying several more times, I experienced the same issue. This was due to the valid JSON data changing to the following:
{"status":{"message":"the daily limit of 30000 credits for demo has been exceeded. Please use an application specific account. Do not use the demo account for your application.","value":18}}
... which lead me to look at the formatting of the data coming from my API (looking at it in Fiddler:
Instead of:
JSON
---{... data...
it's
JSON
---$id=1
---$values
------{}
---------$id=2
---------CREATEDATETIME...
---------EMAIL=email#email.com
---------GROUPS
------------$id=...
------------$id=...
---------USERNAME=someusername
------{}
---------$id=4
.
.
.
So the error is caused by the array not being accessible where the it's expected - instead of the root, it's one level deep.
How do I get data binding to the one-level-deep rather than the root of the JSON object?
Thanks.
I had the same error with a ComboBox that I was using as an autocomplete. In my controller, the return statement was
return Json(model.ToDataSourceResult(dataSourceRequest), JsonRequestBehavior.AllowGet)
which I changed to
return Json(model, JsonRequestBehavior.AllowGet)
This provided the array at the root level instead of one level deep for me.
The solution for this was to traverse the data hierarchy by describing the result format.
Since the array is contained in $values, I used the following data source/schema definition:
// gets data from /api/user
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/user"
}
},
schema: { // describe the result format
data: function(data) { // the data which the data source will be bound to is in the values field
console.log(data.$values);
return data.$values;
}
}
});
One thing that would be nice is to be able to add a data schema type in the Razor helper - which doesn't seem to be supported at this time.
Thus, the following still would not work:
#(Html.Kendo().AutoComplete()
.Name("userAutoComplete") // specifies the "id" attribute of the widget
.Filter("startswith")
.Placeholder("Type user name...")
.DataTextField("USERNAME")
.DataSource(source =>
{
source:
source.Read(read =>
{
read.Url("/api/user");
})
.ServerFiltering(true); // if true, the DataSource will not filter the data on the client
}
)
)
This worked for me:
var dataSource = new kendo.data.DataSource({
transport: {
read:
{
url: "api/dashboard"
}
},
schema: {
**data: function (data)
{
return [data];
}**
}
});
My response wasn't an array, i was returning from the server a response object like this:
{"Field1":0,"Field2":0,"Field3":0}
thanks "brittongr"...that worked for me too. but in my case it is not right, I was building a chart, a chart need an array of course, so instead of altering the schema by converting my Json data to an array I just returned from my action a list having one element. Something like this below.
Random rand = new Random();
int numIterations = 0;
numIterations = rand.Next(1, 1200);
List aux = new List<graphicDataItem>();
aux.Add(new graphicDataItem { ColumnTotal = 1200, ColumnActives = numIterations, ColumnInactives = 1200 - numIterations, ColumnApprovedByMembers = 250, ColumnApprovedByAssoc = 300, XAxisData = DateTime.Now.Year });
return Json(aux, JsonRequestBehavior.AllowGet);
I have "graphicDataItem" type defined on my Entities folder, but is easy to get by looking at the way it is instantiated within the code.
i change for this, and this work for me:
#(Html.Kendo().AutoComplete()
.Name("productAutoComplete") //The name of the autocomplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("myfield") //Specifies which property of the Product to be used by the autocomplete.
.DataSource(source =>
{
source.Custom()
.Type("aspnetmvc-ajax")
.Transport(transport=>
{
transport.Read("MyAction", "Control");
})
.Schema(schema=>schema.Data("Data").Total("Total"))
.ServerFiltering(true); //If true the DataSource will not filter the data on the client.
})
)

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