2013-01-15 37 views
11

背景:PHP中的鬍鬚部分 - 我如何使用它們?

我已經閱讀儘可能多的鬍鬚文檔儘可能多,但我無法讓我的頭周圍如何使用partials甚至我是否正確地使用鬍子。

以下代碼正常工作。我的問題是我有三個Mustache文件,我想一次包含並渲染所有文件。

我在猜測這就是partials的意思,但我似乎無法讓它工作。


問題:

如何讓我的三個鬍子文件被加載,並且都被傳遞$ data變量我會得到泛音在這方面的工作?

我應該以這種方式使用file_get_contents作爲模板嗎?我已經看到鬍鬚功能正在使用,但我找不到足夠的文檔來使其工作。


ENV:

我使用的是最新版本的鬍子從https://github.com/bobthecow/mustache.php

我的文件有:
的index.php(下同)
template.mustache
template1.mustache
template2.mustache
class.php


CODE:

// This is index.php 
// Require mustache for our templates 
require 'mustache/src/Mustache/Autoloader.php'; 
Mustache_Autoloader::register(); 

// Init template engine 
$m = new Mustache_Engine; 

// Set up our templates 
$template = file_get_contents("template.mustache"); 

// Include the class which contains all the data and initialise it 
include('class.php'); 
$data = new class(); 

    // Render the template 
print $m->render($template, $data); 

謝謝:

一個PHP執行分音(包括必要的文件結構將如何需要來定)的任何示例,將不勝感激,只是這樣我才能得到一個堅實的理解:)

+0

讓我建議這個帖子充滿了包括partials在內的例子,但不包括文件結構,因爲這取決於你/你的框架:http://coenraets.org/blog/2011/12/tutorial-html-templates- with-mustache-js/ –

+0

謝謝。真的,我正在尋找使用存儲在單獨文件中的模板的示例的PHP實現。 – Lishamatish

回答

20

最簡單的是使用「文件系統」模板加載器:

<?php 
// This is index.php 
// Require mustache for our templates 
require 'mustache/src/Mustache/Autoloader.php'; 
Mustache_Autoloader::register(); 

// Init template engine 
$m = new Mustache_Engine(array(
    'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__)) 
)); 

// Include the class which contains all the data and initialise it 
include('class.php'); 
$data = new class(); 

// Render the template 
print $m->render('template', $data); 

然後,假設您的template.mustache看起來是這樣的:

{{> template2 }} 
{{> template3 }} 

template2.mustachetemplate3.mustache模板將自動從當前目錄需要時加載。

請注意,此加載程序用於原始模板和部分。如果您有存儲在一個子目錄中的諧音,例如,可以專門增加一個第二裝載機泛音:

<?php 
$m = new Mustache_Engine(array(
    'loader'   => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), 
    'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials') 
)); 

有上the Mustache.php wiki這些和其他Mustache_Engine選項的詳細信息。

+0

非常感謝您的澄清。小鬍子是我使用的第一個模板系統,只需要對文件結構進行一些說明。再次感謝:) – Lishamatish

+2

沒問題。我向Mustache.php wiki中添加了一個模板加載頁面,希望這也有助於澄清 - https://github.com/bobthecow/mustache.php/wiki/Template-Loading – bobthecow

+0

花了些功夫讓我滾動,但效果很好。這將大大簡化我們的平臺模板。從2017年開始感謝! –