有没有办法动态注入(inject)部分模板(并使其在 Ruby 和 Javascript 中以相同的方式工作)?基本上,我试图在列表中呈现不同类型的对象。
我能想到的最好的是:
<div class="items">
{{#items}}
<div class="item">
{{#is_message}}
{{> message}}
{{/is_message}}
{{#is_picture}}
{{> picture}}
{{/is_picture}}
</div>
{{/items}}
</div>
我对这种方法并不太感兴趣。 有没有更好的办法?
另请注意, View 的不同类型模型可能具有不相似的字段。我想我总是可以使用最小公分母并让数据哈希包含 html,但我宁愿使用 mustache 模板。
最佳答案
我做了与您相同的事情,对于每个属性类型我都需要一个动态部分,我只是在模板中呈现的 js 数据模型中设置一个动态变量...
eval("this.set({is_" + this.get("propertyType") + ": true})")
或
this["is_" + propertyType] = true
至少我不必手动设置“is_whatever”变量...
如果 mustache.js 或 ICanHaz.js 对 mustache 标签内的动态属性有一些巧妙的语法,那就太棒了……也许是这样的:
{{>{{message}} }}
关于javascript - 使用 mustache 动态渲染部分模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2932679/