【问题标题】:Can I use a Mustache var in a partial name?我可以在部分名称中使用 Mustache 变量吗?
【发布时间】:2014-12-11 15:22:10
【问题描述】:

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

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

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

但我怎样才能在主模板中做与此等效的事情 (basic.mustache)

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

【问题讨论】:

    标签: mustache mustache.php


    【解决方案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 作为您的“页面”模板:

    {{< 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' =&gt; [Mustache_Engine::PRAGMA_BLOCKS]] 传递给 Mustache_Engine 构造函数以全局启用它们。

    【讨论】:

    • 我尝试按照您的建议使用该块,但有些东西还不起作用stackoverflow.com/questions/27446987/…
    • 如何在页面模板中使用partial? “partials_loader”似乎与“pragmas”不兼容
    • 好的,我意识到我必须将部分保存在与 layout.mustache 相同的文件夹中。谢谢!
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果你像这样提前构建字符串

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

      然后像这样在你的模板中使用

      {{>part}}
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-27
        • 1970-01-01
        • 2018-09-26
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        相关资源
        最近更新 更多