使用 Mustache 动态渲染部分模板
有没有一种方法可以动态注入部分模板(并使其在 Ruby 和 Javascript 中以相同的方式工作)?基本上,我试图在列表中渲染不同类型的对象。
我能想到的最好的办法是:
<div class="items">
{{#items}}
<div class="item">
{{#is_message}}
{{> message}}
{{/is_message}}
{{#is_picture}}
{{> picture}}
{{/is_picture}}
</div>
{{/items}}
</div>
我对这种方法不太感兴趣。 有更好的办法吗?
另请注意,不同类型的视图模型可以具有不相似的字段。我想我总是可以使用最小公分母并让数据哈希包含 html,但是我宁愿使用小胡子模板。
Is there a way to dynamically inject partial templates (and have it work the same way in both Ruby & Javascript)? Basically, I'm trying to render different types of objects in a list.
The best I can come up with is this:
<div class="items">
{{#items}}
<div class="item">
{{#is_message}}
{{> message}}
{{/is_message}}
{{#is_picture}}
{{> picture}}
{{/is_picture}}
</div>
{{/items}}
</div>
I'm not super-psyched about this approach.
Is there a better way?
Also note that the different types of models for the views can have non-similar fields. I suppose I could always go to the lowest common denominator and have the data hash contain the html, however I would rather use the mustache templates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我做了和你一样的事情,对于每个属性类型,我需要一个动态部分,我只是在模板中渲染的 js 数据模型中设置一个动态变量......
或者
至少我不必手动设置'is_whatever' 变量...
如果 Mustache.js 或 ICanHaz.js 对于 Mustache 标签内的动态属性有一些巧妙的语法,那就太酷了...也许是这样的:
I did the same thing you did, and for each property type i needed a dynamic partial, I just set a dynamic variable in the js data model that's being rendered in the template...
or
At least I don't have to manually set the 'is_whatever' variable...
It would be cool if mustache.js or ICanHaz.js had some clever syntax for dynamic properties inside of mustache tags... maybe something like this: