如果我从一个八字胡脚本和一些分词来渲染HTML,我可以根据渲染的数据来选择使用哪个分词吗?
例如:
data = {"posts": [
{"type":"text", "body":"I'm text"},
{"type":"image", "uri":"http://placekitten.com/200/300"}
]}使用的基本模板如下:
<ul class="posts">
<li>
{{#posts}}
{{> {{type}}}}
{{/posts}}
</li>
</ul>然后是text.mustache
<p>{{body}}</p>和image.mustache
<img src="{{uri}}" />这将呈现为:
<ul class="posts">
<li>
<p>I'm text</p>
</li>
<li>
<img src="http://placekitten.com/200/300" />
</li>
</ul>我是不是漏掉了什么?我应该尝试这样做吗?
发布于 2013-03-13 05:17:32
您在这里提出的问题属于“逻辑”方面,因此,Mustache试图避免这样的问题。这并不是说没有办法做到这一点,只是它可能不是你想的那样:)
在Mustache中,对于许多更高级的用法,正确的答案是“准备您的视图”。这也不例外。我很可能会这样做:
function addHelpers(posts) {
for (var i = 0, l = posts.length; i < l; i++) {
posts[i].isText = posts[i].type === 'text';
posts[i].isImage = posts[i].type === 'image';
posts[i].isVideo = posts[i].type === 'video';
}
return posts;
}
data = {"posts": [
{"type":"text", "body":"I'm text"},
{"type":"image", "uri":"http://placekitten.com/200/300"}
]}
data.posts = addHelpers(data.posts);然后,您的基本模板将如下所示:
<ul class="posts">
{{# posts }}
<li>
{{# isText }}{{> text }}{{/ isText }}
{{# isImage }}{{> image }}{{/ isImage }}
{{# isVideo }}{{> video }}{{/ isVideo }}
</li>
{{/ posts }}
</ul>https://stackoverflow.com/questions/15345914
复制相似问题