我正在为周末开始的项目留下小胡子。
我正在使用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>
bottom.mustache:
</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 }}
这是正确的做法吗?
答案 0 :(得分:6)
以下是一个如何使用Mustache的php实现的示例。值得注意的是,Mustache.php将不扩展包含的部分/模板,因此您必须将它们交给胡须,如下所示。这个例子拼凑在一个较旧的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>
<强>共享/ logged_in_user_box.mustache 强>
Hello {{display_name}}, you are logged in.
<强>共享/ logged_out_user_box.mustache 强>
Hello. You are not logged in.
答案 1 :(得分:4)
ynkr的答案适用于旧版本,但我刚刚升级到版本2.4.1,如果你使用的是filesystemloader,那么你的方法应该可行。
有关详细信息,请参阅https://github.com/bobthecow/mustache.php/wiki/Template-Loading#partials-loading。