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.
Related
please check the below code what i have in my aspx page. Please help me in this.
I am trying to nesting one template into another but i am not getting proper output.
My output:
Application1
#childTemplate
My expected output:
Application1
Env1
Env2
$(document).ready(function()
{
var mydata:[{Application: "Application1",Environment[{Env:"Env1"},{Env:"Env2"}]}];
$("#parentTemplate").tmpl(mydata).append("#divEnvironment");
});
<script id="parentTemplate" type="text/x-jquery-tmpl">
<ul><li>${Application}</li></ul>
{{tmpl{$data} "#childTemplate"}}
</script>
<script id="childTemplate" type="text/x-jquery-tmpl">
{{each Environment}}
<p>${Env}</p>
{{/each}}
</script>
<div id="divEnvironment"></div>
I am trying to build a simple page, which will calculate your stake and work out your return, like a betting shop.
So far, I have it working by hard coding in my odds. But as you will see in my code, I have the odds pulling through in an alert, which works well. My issue is trying to incorporate this variable into my html, I get the output of "NaN", but I have no clue why! My attempt is commented out, but hopefully this is an easy fix, which I just can't see!
My HTML:
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title></title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://localhost:8888/json.json", function(result){
$.each(result, function(i, field){
//create an element and append data attribute to the element - in this case field name
el = $("<div class='bet-block'>" + field.name + field.odds.numerator+"/" + field.odds.denominator + " </div>").data("name", field.name).data("odds", field.odds.numerator+"/" + field.odds.denominator);
//append element to DOM
$(".bets").append( el );
})
//define a click handler for all new elements to display data in a div
$(document).on( "click", ".bet-block", function() {
$(".bet-name").text( $( this ).data("name") );
$(".bet-odds").text( $( this ).data("odds") );
});
});
function calculate_odds() {
var winnings = 0,
betting_amount = $(".stake").val();
var current_odds = $('.bet-odds').text();
// THIS ECHOS CORRECT ODDS
alert(current_odds);
winnings = (2/1) * betting_amount;
// winnings = (current_odds) * betting_amount;
$('.js-winnings').text(winnings);
}
$(document).ready(function() {
$(".stake").keyup(function(){
calculate_odds();
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="bets">
<h1>All Bets</h1>
</div>
</div>
<div class="col-md-4">
<div class="slip">
<h1>My Bet Slip</h1>
<div class="new-bet-slip">
<p><span class="bet-name"></span> to win # <span class="bet-odds"></span></p>
<input class="stake" type="number" name="betting-amount" min="1" max="5">
<div class="bet-return">
<span>£</span><span class="js-winnings">0.00</span>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
My JSON:
[{"name":"name1","odds":{"numerator":10,"denominator":1}},[{"name":"name2","odds":{"numerator":5,"denominator":2}}, [{"name":"name3","odds":{"numerator":2,"denominator":1}}, ]
Thanks in advance!
The JSON data you entered is not formatted properly, check the square brackets and try again. This site is helpful for that purpose: https://jsonformatter.curiousconcept.com/
as #gujefers pointed out: Your current_odds which is declared as:
var current_odds = $('.bet-odds').text();
Returns string refer to http://api.jquery.com/text/
So when you try to do arithmetic operation on string which is * in winnings = (current_odds) * betting_amount; You get NaN (not a number) error.
So the safe bet would be try converting the string value to int. parseInt function converts string to int
for example try this is console:
var a = '1';
var b = parseInt(a);
console.log(typeof(a)); //this will return string
console.log(typeof(b)); //this will return number
I hope this may help you...
$.getJSON("http://localhost:8888/json.json", function(result){
//parse the json & try
var data= jQuery.parseJSON(result);
$.each(data, function(i, field){
//do your action
console.log(field.name)
$.each(field.odds, function(k, level2){
console.log(level2.numerator,level2.denominator)
});
});
});
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
this might be real simple but I've tried many examples and still couldn't make it working.
So I've got this code to check if the entry is written by the author and if so, I want to print it into template.
function printTitltes() {
var currentUser = JSON.parse(localStorage.getItem('currentUser'))
var author = currentUser["username"];
var allEntries = JSON.parse(localStorage.getItem("allEntries"));
var template = Handlebars.compile($("#template").html());
var authorEntry;
if (!allEntries) {
return
} else {
for (var i=0; i<allEntries.length; i++) {
if (allEntries[i]["author"] === author) {
authorEntry = allEntries[i];
$("#titleArea").append(template(authorEntry));
}
}
}
}
And my template is:
<script type='text/template' id='template'>
<ul class="entries-list">
{{#each auhorEntry}}
<li data-id="{{ID}}">
<span> {{date}} </span>
{{title}}
</li>
{{/each}}
</ul>
</script>
When executed, all I got is an empty template. I've must have been sending a wrong object to the template but couldn't grasp how could I do it right. Anyone whould spot it for me please?
<script type="text/x-handlebars-template" id="template">
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.