15

環境:

Mustache のドキュメントをできる限り読みましたが、パーシャルの使用方法や、Mustache を正しい方法で使用しているかどうかさえもわかりません。

以下のコードは正しく動作しています。私の問題は、一度に含めてレンダリングしたい 3 つの Mustache ファイルがあることです。

これがパーシャルの目的であると推測していますが、機能させることができないようです。


質問:

3 つの Mustache ファイルがロードされ、すべてが $data 変数に渡されるように、このコンテキストでパーシャルを動作させるにはどうすればよいでしょうか?

テンプレートにこの方法で file_get_contents を使用する必要がありますか? その代わりに Mustache 関数が使用されているのを見たことがありますが、それを機能させるのに十分なドキュメントが見つかりません。


環境:

https://github.com/bobthecow/mustache.phpの最新バージョンの Mustache を使用しています。

私のファイルは次のとおりです:
index.php (以下)
template.mustache
template1.mustache
template2.mustache
class.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;

// 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 実装の例 (必要なファイル構造がどのように必要になるかを含む) は、私がしっかりと理解できるように、大歓迎です:)

4

1 に答える 1

25

最も簡単なのは、「ファイルシステム」テンプレートローダーを使用することです。

<?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.mustacheおよびtemplate3.mustacheテンプレートは、必要に応じて現在のディレクトリから自動的にロードされます。

このローダーは、元のテンプレートとパーシャルの両方に使用されることに注意してください。たとえば、パーシャルをサブディレクトリに保存している場合は、パーシャル専用の2番目のローダーを追加できます。

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

Mustache.php wikiには、これらのオプションやその他のMustache_Engineオプションに関する詳細情報があります。

于 2013-01-15T18:22:58.787 に答える