10

我正在为周末开始的一个项目留胡子。

我正在使用 PHP 实现。但是,我有一些询问,因为我不习惯该系统。

您如何处理模板继承或重用?我知道部分,但我应该如何使用它们?我正在做这样的事情,包括:

top.mustache:

<!DOCTYPE html>
<html lang='es'>
<head>
    <meta charset=utf-8" />
    <link rel="stylesheet" href="/media/style.css" type="text/css" media="screen" />
</head>
<body>
     <header><h1><a href="/">Top</a></h1>
     </header>
     <section>

底部. 小胡子:

        </section>
        <footer><a href="http://potajecreativo.com/">potaje</a></footer>
</body>
</html>

以及呈现此模板的视图:

{{>top}}
<form action="/album/" method="post">
    <p><label for="name">Name</label> <input type="text" name="name" value=""/></p>
    <p><label for="description">Description</label> <textarea name="description" rows="8" cols="40"></textarea></p>
    <p><input type="submit" value="Save" /></p>
</form>
{{>bottom }}

这是正确的方法吗?

4

2 回答 2

6

以下是 Mustache 的 php 实现如何工作的示例。值得注意的是 Mustache.php不会扩展包含的部分/模板,因此您必须将它们交给 mustache,如下所示。这个例子是在一个旧的 cakephp 框架上拼凑而成的。

<?
  # php cannot recognize multiple acceptable file extensions for partials,
  # so toggle it to mustache's extension
  $this->ext = '.mustache';

  # Mustache says it's logic-less, but that's not exactly true.
  # Render out the basic header which calls the logo partial and has
  # a {{# logged_in? }} condition which dictates which user box we
  # show. Thus, we need to render out the html for both the logged in
  # and logged out user boxes
  $basic_header_html = $this->renderElement('basic_header');
  $logo       = $this->renderElement('shared/logo');
  $logged_in  = $this->renderElement('shared/logged_in_user_box');
  $logged_out = $this->renderElement('shared/logged_out_user_box');

  $m = new Mustache($basic_header_html,                    
                    array('logged_in?' => !empty($this->Auth->userData),
                          'cache_buster' => time(),
                          'display_name' => 'StackOverflow Customer'),
                    array('shared/logo' => $logo,
                          'shared/logged_in_user_box' => $logged_in,
                          'shared/logged_out_user_box' => $logged_out));
?>

<!DOCTYPE html>
<html>
<head>
  <title>Mustache Test</title>
</head>

<body>
  <?= $m->render(); ?>
</body>
</html>

basic_header.mustache

<div id="header" class="basic">
  {{> shared/logo }}

  {{# logged_in? }}
    {{> shared/logged_in_user_box }}
  {{/ logged_in? }}

  {{^ logged_in? }}
    {{> shared/logged_out_user_box }}
  {{/ logged_in? }}
</div>

共享/logo.mustache

<a class="logo" href="/foo/bar"><img alt="" src="/images/logo.png?{{ cache_buster }}" /></a>

shared/logged_in_user_box.mustache

Hello {{display_name}}, you are logged in.

shared/logged_out_user_box.mustache

Hello. You are not logged in.
于 2011-02-15T21:57:36.563 回答
4

ynkr 的答案适用于旧版本,但我刚刚升级到版本 2.4.1,如果您使用文件系统加载器,您的方法应该可以工作。

有关详细信息,请参阅https://github.com/bobthecow/mustache.php/wiki/Template-Loading#partials-loading

于 2013-08-20T10:14:04.363 回答