我正尝试在我的Handlebar模板中执行条件语句。问题是,如果插入了if条件,它根本不会呈现内容。
下面是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Handlebars.js example</title>
</head>
<body>
<div id="placeholder">This will get replaced by handlebars.js</div>
<script type="text/javascript" src="handlebars.js"></script>
<script id="myTemplate" type="text/x-handlebars-template">
{{#names}}
<div style="width:100%;border:2px solid red;">
<table style="width:100%;border:2px solid black">
<tr>
<td style="width:50%; border:2px solid yellow;">
<img src="{{itemImage}}"></img>
</td>
<td style="width:50%; border:2px solid green;">
<img src="btn_downloadAudio.png"></img><br><br>
<img src="btn_downloadPresentation.png"></img><br><br>
<img src="btn_downloadTranscript.png"></img><br><br>
<img src="btn_downloadVideo.png"></img><br><br>
</td>
</tr>
<tr>
<td colspan="2"><img src="{{itemType}}">
<label style="font-weight:bolder">{{itemTitle}}</label>
</td>
</tr>
<tr>
<td colspan="2">
<p>{{itemDescription}}</p>
</td>
</tr>
</table>
</div>
{{/names}}
</script>
<script type="text/javascript">
var source = document.getElementById("myTemplate").innerHTML;
var template = Handlebars.compile(source);
//alert(template);
var data = {
names: [
{ "itemImage": "authorImage.png",
"itemTitle": "Handlebars.js Templating for HTML",
"itemType": "icon_document.png",
"isAudioAvailable": "true",
"isPresentationAvailable": "true",
"isTranscriptAvailable": "true",
"isVideoAvailable": "false",
"itemDescription": "Rendeting HTML content using Javascript is always messy! Why? The HTML to be rendered is unreadable. Its too complex to manage. And - The WORST PART: It does it again and again and again! Loss: Performance, Memory, the DOM has to be re-drawn again each and every time a tag is added."}
]
};
document.getElementById("placeholder").innerHTML = template(data);
</script>
</body>
</html>条件:如果isVideoAvailable为true,则显示视频按钮
任何帮助都是非常感谢的。
谢谢,安吉特
发布于 2013-07-12 02:21:23
如果您希望有条件地显示某些内容,则可以使用{{#if}}
{{#if isVideoAvailable}}
<img src="btn_downloadVideo.png"><br><br>
{{/if}}当然,为了让它正常工作,您的数据应该是有意义的,并且isVideoAvailable应该是布尔值。因此,您还需要清理数据才有意义,isVideoAvailable应该是true或false,而不是字符串'true'或'false';预处理数据在Handlebars中非常常见,因此修复数据将是最好的做法,修复数据也可以让您在JavaScript中以自然的方式使用数据。
演示:http://jsfiddle.net/ambiguous/LjFr4/
但是,如果您坚持将布尔值保留为字符串,那么您可以添加一个if_eq帮助器并如下所示:
{{#if_eq isVideoAvailable "true"}}
<img src="btn_downloadVideo.png"><br><br>
{{/if_eq}}清理你的数据会是一个更好的主意。
https://stackoverflow.com/questions/17599378
复制相似问题