I have code below. I need to populate a JSON object using mustache. Unfortunately, it shows nothing to me.
<script type="text/javascript">
var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]";
var template = $("#template").html();
Mustache.parse(template);
var rendered = Mustache.render(template, data);
$('#PatrList').html(rendered);
</script>
<body>
<div id="PatrList"></div>
<script id="template" type="x-tmpl-mustache">
{{ #. }}
<div>
PR_ID: <h2> {{PR_ID}} </h2> ---- P_ID: <h2> {{P_ID}} </h2>
</div>
{{ /. }}
</script>
</body>
The problem is that var data is a string and not an object. You need to remove the outer quotation marks or parse the string to an object (given that the delimiter is escaped properly within the string) e.g. with JSON.parse(str) or eval
Related
I am new to webdevelopment. So, Here, I have textAngular. In this I a, showing html document. Now, I want to show the text of the document only but that should be with the formatting as it is in the .html file. So,Right now my code is like -
here data is the html file content, you can say it's a string which has the html file content.Now,
$scope.htmlOriginalDoc = parser.parseFromString(data, 'text/html');
$rootScope.data.htmlDocument = $scope.htmlOriginalDoc.body.innerText;
So, Here when I get this that time I am getting all the data of that file, but when I see it it is like just a text document it is not having any new lines,I mean its not preserving the new line or spaces .So, How can I achieve this ?
Basically you need to compile it from string, then bind it with ngSanitize. To preserve the white space wrap with <pre> tags.
var app = angular.module('myApp', ['ngSanitize']);
app.controller('myCtrl', function($scope, $sce) {
$scope.html = "<div style=\"color:red;font-size:24px;\"> T e s t </div>"; // string
$scope.html = $sce.trustAsHtml($scope.html);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-sanitize.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div style="white-space: pre;"> <!-- instead of <pre> -->
<div ng-bind-html="html"></div>
</div>
</div>
I am having my first play with HandlebarsJS and I am looking to use multiple arrays within it. Is this possible?
I have setup a Codepen template but I am struggling to implement the data from 2 arrays and from an external URL. I have tried this with MustacheJS too, but I believe that only allows one array and no filtering- unlike Handlebars
Here is the external JSON
and the CodePen
<!-- REQUIRED - Display site name, url and title in top section. With product data below using the "other array-->
<script id="myTemplate" type="text/x-handlebars-template">
{{content}}
</script>
<div id="contentArea"></div>
<script>
var data = {"content": "Hello, World!"};
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(data);
$("#contentArea").text(html);
</script>
Here is my first template attempt but failing to integrate the JSON array at the moment
It's possible using {{#each}} block helper. I also registered my own helper {{{s}}}, which simply returns it's argument JSON.stringify()'ied, so I can print those arrays. How you fetch them is another problem, I Copy & Paste them into the Javascript part of the code for simplicity. Also, here's JS fiddle:
var data = {"content": "Hello, World!", "multipleArrays": [
[
{
"productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/i0lfddlghaiwfqlvlqay/air-vortex-shoe-fmq6pS.jpg",
"producturl": "https://www.nike.com/gb/t/air-vortex-shoe-fmq6pS"
},
{
"productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/cmuof8adhfipkvd0f43r/air-max-95-shoe-XPTbV2mM.jpg",
"producturl": "https://www.nike.com/gb/t/air-max-95-shoe-XPTbV2mM"
}
],
[
{
"sitename": "Nike",
"sitetitle": "Nike. Just Do It.. Nike.com",
"siteurl": "https://www.nike.com/gb/en_gb/"
}
]
]};
Handlebars.registerHelper('s', function(arg) {
return JSON.stringify(arg);
})
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(data);
$("#contentArea").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/handlebars.js/4.0.11/handlebars.min.js"></script>
<!-- REQUIRED - Display site name, url and title in top section. With product data below using the "other array-->
<script id="myTemplate" type="text/x-handlebars-template">
<h1>Content: {{content}}</h1>
<hr>
<h2>Stringified multiple arrays:</h2>
{{{s multipleArrays}}}
<hr>
{{#each multipleArrays}}
<h2>Item {{#index}}</h2>
{{{s this}}}
<br>
<br>
{{/each}}
</script>
<div id="contentArea">
</div>
I want to make certain elements lowercase by using handlebars (I know it's possible with CSS, but you can't do that for classnames for example). Anyhow, I am getting this error:
Uncaught Error: toLowerCase doesn't match each
My code:
<script id="icon-template" type="text/x-handlebars-template">
{{#each results}}
<li>
<div class="content">
<i class="Icon icon-{{#toLowerCase contentType}}"></i>
</div>
</li>
{{/each}}
</script>
Custom helper:
<script type="text/javascript">
Handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
What am I doing wrong?
I figured it out. For anyone having the same problems:
<script type="text/javascript">
handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
Handlebars must have a lowercase letter (like this: handlebars) at first & no hashtag is needed when you are using a custom helper. So the custom helper is now toLowerCase instead of #toLowerCase
<script id="icon-template" type="text/x-handlebars-template">
{{#each results}}
<li>
<div class="content">
<i class="Icon icon-{{toLowerCase contentType}}"></i>
</div>
</li>
{{/each}}
</script>
If a handlebars helper name is all lowercase:
<script type="text/javascript">
handlebars.registerHelper("lower", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
you will need to use the hash when invoking it:
<script id="icon-template" type="text/x-handlebars-template">
<i class="Icon icon-{{#lower contentType}}"></i>
</script>
If the helper uses a CamelCase name:
<script type="text/javascript">
handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
then you do not use the hash:
<script id="icon-template" type="text/x-handlebars-template">
<i class="Icon icon-{{toLowerCase contentType}}"></i>
</script>
It matters how you invoke the helper. If you use a hash(#) then it's considered a Block Helper and needs to be closed. Otherwise you'll get that parsing error.
{{#toLowerCase}}Some UPPERCASE text{{/toLowerCase}}
Obviously it also matters what the helper code does. The syntax above is correct but the code may not have the desired effect.
I want to hand over a stringarray from my views.py to the template and use this strings for D3.
views.py:
def index(request):
template = loader.get_template("myApp/index.html")
data = ["a","b","c"]
context = RequestContext(request,{"data":data})
return HttpResponse(template.render(context))
index.html:
<html>
<head>
<title>Some project</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<h1>Some project visualisation</h1>
<script type="text/javascript">
var dataArray = {{ data }};
...
At "var dataArray = {{ data }};" I get a syntax error.
I looked this up in the browser-console and my dataArray
seems to look like this:
var dataArray = ['a','b','c']
I have also tried to use json.dumps(data), but I get a similar dataArray like:
var dataArray = ["a","b","c"]
What you are searching for is the 'safe' filter:
context = RequestContext(request,{"data":json.dumps(data)})
...
<script type="text/javascript">
var dataArray = {{ data | safe }};
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-safe
If you use variables more often in your javascript, it would probably make sense to turn off autoescape
I created a helper in Handlebars to help with logic, but my template parses the returned html as text rather than html.
I have a quiz results page that is rendered after the quiz is completed:
<script id="quiz-result" type="text/x-handlebars-template">
{{#each rounds}}
{{round_end_result}}
{{/each}}
<div class="clear"></div>
</script>
For each of the rounds, I use a helper to determine which template to render a round's result:
Handlebars.registerHelper("round_end_result", function() {
if (this.correct) {
var source = '';
if (this.guess == this.correct) {
console.log("correct guess");
var source = $("#round-end-correct").html();
} else {
var source = $("#round-end-wrong").html();
}
var template = Handlebars.compile(source);
var context = this;
var html = template(context);
console.log(html);
return html;
} else {
console.log("tie");
}
});
Here is a template that describes a correct round (let's take say it rendered the #round-end-correct template):
<script id="round-end-correct" type="text/x-handlebars-template">
<div></div>
</script>
Here is what gets rendered:
<div></div>
Not as HTML, but as text. How do I get it to actually render the HTML as HTML, rather than text?
I assume that unescaping in Handlebars works the same as in vanilla Mustache.
In that case use triple mustaches to unescape html, i,e: {{{unescapedhtml}}}, like:
<script id="quiz-result" type="text/x-handlebars-template">
{{#each rounds}}
{{{round_end_result}}}
{{/each}}
<div class="clear"></div>
for ref see:
http://mustache.github.com/mustache.5.html
Geert-Jan's answers is correct but just for reference you can also set the result to "safe" directly inside the helper (code from handlebars.js wiki)
Handlebars.registerHelper('foo', function(text, url) {
text = Handlebars.Utils.escapeExpression(text);
url = Handlebars.Utils.escapeExpression(url);
var result = '' + text + '';
return new Handlebars.SafeString(result);
});
With that you can use regular double handlebars {{ }} and handlebars won't escape your expression.