2010-11-15 31 views
10

我正在爲我在週末開始的一個項目收集鬍子。小鬍子部分和代碼重用

我正在使用PHP實現。不過,由於我不習慣這個系統,所以我有一些問題。

如何處理模板的繼承或重用? 我知道partials,但我應該如何使用它們?我在做這樣的事情,阿拉包括:

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 }} 

這是正確的做法嗎?

回答

6

下面是鬍子的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. 
+5

我假設你在你的例子中使用了Cake框架,儘管在問題或你的答案中沒有提到這個。你可能想澄清一下,在你的答案中,讓它更容易混淆。 – jsdalton 2011-12-14 19:56:10