是否可以根据 Mustache 中的哈希值切换模板部分?
好的,所以我正在尝试掌握 Mustache.js 以在 javascript 中渲染视图。我有一个 API,它返回多个“事件”,这些“事件”可以是多种不同类型。我想根据事件的类型以(非常)不同的方式呈现事件:
data : {
events: [ {title: 'hello', type: 'message'}, {title: 'world', type: 'image'} ] }
理想情况下,我可以这样做:
{{#events}}
{{#message}}
<div class="message">{{title}}</div>
{{/message}}
{{#image}}
<span>{{title}}</span>
{{/image}}
{{/events}}
但这会(对吗?)迫使我将数据重构为:
data : {
events: [ {message: {title: 'hello'}}, {image: {title: 'world'}} ] }
是否有更好的方法来解决这个问题,而不重构我的数据?或者我应该硬着头皮?
Ok, so I'm trying to get a grip on Mustache.js for rendering views in javascript. I have an API that returns a number of "events", which can be a number of different types. I want to render the events in (very) different ways, based on their type:
data : {
events: [ {title: 'hello', type: 'message'}, {title: 'world', type: 'image'} ] }
Ideally, I could do something like this:
{{#events}}
{{#message}}
<div class="message">{{title}}</div>
{{/message}}
{{#image}}
<span>{{title}}</span>
{{/image}}
{{/events}}
But that would (right?) force me to refactor my data into:
data : {
events: [ {message: {title: 'hello'}}, {image: {title: 'world'}} ] }
Is there a better way of solving this, without refactoring my data? Or should I just bite the bullet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mustache 缺乏逻辑,因此除了切换到 Handlebars。
您的 Mustache 友好替代方案是声明一个助手并使用它来选择要呈现的模板。它变得有点复杂,但如果这是您无法更改的内容,您可以避免从 Mustache 切换:
这里的技巧是您创建一个将作为迭代器的基本模板,并传入
event_renderer
作为一个帮手。该助手将再次调用 Mustache.render,使用部分来渲染您可以拥有的每种类型的事件(即 {{>partial}} 表示法)。这里唯一难看的部分是您需要将此
event_renderer
成员添加到您的 JSON 数据中,但除此之外,一切都应该没问题(在 Handlebars 中,您可以将其声明为助手,不需要将其与您的数据合并)。Mustache is logic-less so there's not much you can do with pure template code other than switching to Handlebars.
Your Mustache-friendly alternative would be to declare a helper and use it to select which template to render. It gets a little convoluted but you can avoid switching away from Mustache if that's something you can't change:
The trick here is that you create a base template that will be the iterator, and pass in
event_renderer
as a helper. That helper will in turn call Mustache.render again, using partials to render each type of event you can have (that's the {{> partial}} notation).The only ugly part here is that you need to add this
event_renderer
member to your JSON data, but other than that, it should all be fine (in Handlebars you could declare it as a helper and there's no need to merge it with your data).