我可以在部分名称中使用Mustache var吗?

时间:2014-12-11 15:22:11

标签: mustache mustache.php

我目前使用多个页面(basic.mustache)的模板,一切都很好,但我想添加不同的框(box1.mustache,box2.mustache)在侧边栏中,取决于页面。

基本上,我需要在模板解析的对象中添加胡子模板。

{
  title: "My page tile",
  content: ...
  sidebar: [
    "box1.mustache",
    "box2.mustache"
  ]
}

但是如何在主模板(basic.mustache)中执行与此相同的操作?

{{#sidebar}}
  {{>.}}
{{/sidebar}}

3 个答案:

答案 0 :(得分:1)

不,不可能这样做。但它仍然有可能实现你正在寻找的东西。 See this answer for one answer

不过,看看你的例子,我认为通过模板继承(BLOCKS pragma)可以更好地解决你所寻找的问题。

所以你有layout.mustache作为你的父母"模板:

<!DOCTYPE html>
<html>
  <head>
    <title>{{$ title }}My site has a title!{{/ title }}</title>
  </head>
  <body>
    <section id="main">
      {{$ content }}{{/ content }}
    </section>
    <section id="sidebar">
      {{$ sidebar }}{{/ sidebar }}
    </section>
  </body>
</html>

my_page.mustache作为您的&#34;页面&#34;模板:

{{< layout }}

  {{$ title }}This page has its own title!{{/ title }}

  {{$ sidebar }}
    {{> box1 }}
    {{> box2 }}
  {{/ sidebar }}

  {{$ content }}
    Here's all your awesome content!
  {{/ content }}

{{/ layout }}

注意my_page如何将box1box2部分加载到{{$ sidebar }}块中。您甚至可以通过将默认侧边栏部分添加到主布局中的{{$ sidebar }}块来实现默认侧边栏部分(就像那里的默认{{$ title }}一样)。

请注意,BLOCKS是一个编译指示,因此默认情况下不会在Mustache.php中启用。要使用它,您必须将{{% BLOCKS }}添加到任何一行中带有块的模板,或者将['pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]]传递给Mustache_Engine构造函数以在全局范围内启用它们。

答案 1 :(得分:0)

一些Mustache实现回答了这个常见的问题,支持&#34;动态部分&#34;。请参阅https://github.com/thelucid/tache(Ruby)和https://github.com/groue/GRMustache/blob/master/Guides/rendering_objects.md#example-dynamic-partials(Objective-C)。

答案 2 :(得分:0)

如果您像这样构建字符串

... part: "{{>" + MyPartialName + "}}"

然后在你的模板中使用

{{>part}}

似乎有效。我还没有在原始的JS实现中测试过这个(使用.net),所以一些确认会很好。