0

如果我从 mustache 脚本和一些部分渲染 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>

我在这里错过了什么吗?我应该尝试这个吗?

4

1 回答 1

1

您在这里要问的问题归结为“逻辑”方面,因此,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>
于 2013-03-12T21:17:31.970 回答