以下是 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.