使用 Mustache 动态渲染部分模板

发布于 2024-09-03 18:10:53 字数 442 浏览 2 评论 0原文

有没有一种方法可以动态注入部分模板(并使其在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉默的熊 2024-09-10 18:10:53

我做了和你一样的事情,对于每个属性类型,我需要一个动态部分,我只是在模板中渲染的 js 数据模型中设置一个动态变量......

eval("this.set({is_" + this.get("propertyType") + ": true})")

或者

this["is_" + propertyType] = true

至少我不必手动设置'is_whatever' 变量...

如果 Mustache.js 或 ICanHaz.js 对于 Mustache 标签内的动态属性有一些巧妙的语法,那就太酷了...也许是这样的:

{{>{{message}} }}

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...

eval("this.set({is_" + this.get("propertyType") + ": true})")

or

this["is_" + propertyType] = true

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:

{{>{{message}} }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文