我正在Handlebars模板中编写一个{{#if}}块,但是如果要处理我从脚本切换语句获取的标志值,我想要这个。如何在Handlebars.js中实现这一目标
我想在if块中使用标志值,我该怎么做。
的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>
请分享一些例子,会非常有帮助。
答案 0 :(得分:1)
这是Handlebars的工作方式:
模板
<a href="{{url}}">
{{~#if test}}
{{~title}}
{{~^~}}
Empty
{{~/if~}}
</a>
yourScript
var template = Handlebars.compile(source, { test: true });
对于此示例,我需要在编译模板之前传递测试值以获取正确的模板。在您的代码中,您应该在设置标志变量时调用最终的编译函数。像这样:
if (value.match(emailPattern)) {
console.log('correct');
flag=1;
} else {
console.log('incorrect');
flag=2;
}
var template = Handlebars.compile(source, { error: flag });
在你的模板中:
{{~#if error}}
<div class="hideError">{{~errorBlank}}</div>
{{~/if~}}
您可以在文档中看到更多示例: