Reputation: 810
I am writing a {{#if}} block in Handlebars template, but I want this if to work on the flag value which I am getting from script switch statement. How can be this achieved in Handlebars.js
I want to use the flag value in the if block here, how can i do that.
Script.js
$(document).ready(function(){
var source = $("#forgotPasswordPage-template").html();
var template = Handlebars.compile(source);
var dataForgotPasswordFormElements = {forgotPasswordFormElement:[
{formElement: "emailId" , dataType:"text" , label :"Email Id", errorBlank:"Please enter Email Id"},
{formElement: "oldPassword" , dataType:"password" , label:"Old Password" , errorBlank:"Please enter old password"},
{formElement: "newPassword" , dataType:"password" , label:"New Password", errorBlank:"Please enter new password"},
{formElement: "confirmPassword" , dataType:"password" , label:"Confirm Password", errorBlank:"Please confirm new password"},
{formElement: "hintQuestion" , dataType:"text" , label:"Hint Question", errorBlank:"Please enter hint question"},
{formElement: "hintAnswer" , dataType:"text" , label:"Hint Answer",errorBlank:"Please enter hint answer"},
]};
$("#forgotPasswordPage-placeholder").html(template(dataForgotPasswordFormElements));
$( "#forgotPassword .newField input " ).each(function( index ) {
var newPasswordValue="";
$(this).focusout(function(){
var flag=0;
var value = $(this).val();
var emailPattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i ;
if(value!=""){
if (value.match(emailPattern))
{console.log('correct');
flag=1;}
else
{console.log('incorrect');
flag=2;}
}
Template.html
<script id="forgotPasswordPage-template" type="text/x-handlebars-template">
{{#forgotPasswordFormElement}}
<div class="newField">
<label for="{{formElement}}">{{label}}</label>
<br/>
<input type="{{dataType}}" data-role="none" id="{{formElement}}"></input>
{{#if}}
<div class="hideError">{{errorBlank}}</div>
{{/if}}
</div>
{{/forgotPasswordFormElement}}
</script>
Please share some example, would be very helpful.
Upvotes: 0
Views: 1291
Reputation: 1681
This is the way Handlebars works:
template
<a href="{{url}}">
{{~#if test}}
{{~title}}
{{~^~}}
Empty
{{~/if~}}
</a>
yourScript
var template = Handlebars.compile(source, { test: true });
for this example I need to pass the test value before to compile the template to get the correct template. In your code, you should call the compile function at the end when you have set the flag variable. Something like this:
if (value.match(emailPattern)) {
console.log('correct');
flag=1;
} else {
console.log('incorrect');
flag=2;
}
var template = Handlebars.compile(source, { error: flag });
in your template:
{{~#if error}}
<div class="hideError">{{~errorBlank}}</div>
{{~/if~}}
You could see more examples in the documentation:
http://handlebarsjs.com/expressions.html
Upvotes: 1