Upload
others
View
10
Download
0
Embed Size (px)
Citation preview
Phly\Mustache - MustacheImplementation in PHP 5.3
DocumentationRelease 1.2.0dev
Matthew Weier O’Phinney
January 07, 2015
Contents
1 phly_mustache 3
2 Installation 52.1 Via Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Via a PSR-0 autoloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3 Built-in autoloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.4 Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Usage 7
4 Rendering 94.1 Overview: Templates and Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94.2 Rendering String Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104.3 Rendering File Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104.4 Template Suffix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.5 Rendering Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.6 Rendering methods which return a value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5 Syntax 135.1 Escaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.2 Prevent Escaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.4 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145.5 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155.6 Higher Order Sections Render Inside Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.7 Rendering Nested Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.8 Inverted Sections Render On Empty Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.9 Partials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.10 Aliasing Partials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195.11 Alternate Delimiters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205.12 Alternate Delimiters in selected areas only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205.13 Alternate Delimiters Apply To Child Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215.14 Recursive Partials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215.15 PHP functions will not work inside templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225.16 Hierarchical / Template Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6 Pragmas 256.1 Pragmas Are Section Specific . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256.2 Pragmas Do Not Extend To Partials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
i
6.3 Implicit Iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
7 Resolvers 297.1 The ResolverInterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297.2 The DefaultResolver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297.3 Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
8 Api docs: 31
9 Indices and tables 33
ii
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
Phly\Mustache is a PHP 5.3 implementation of Mustache, a lightweight templating specification.
Contents:
Contents 1
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
2 Contents
CHAPTER 1
phly_mustache
phly_mustache is a Mustache implementation written for PHP 5.3+. It conforms to the principles of mustache ,and allows for extension of the format via pragmas.
Mustache is primarily a syntax and specification for templating. The basic concepts are:
• Templates, which contain a variety of tokens, delimited with double braces, or mustaches: {{ and }}. Thesetypically are used for variable substitution, but a variety of simple control structures and mechanisms for dealingwith iterable or hierarchical datasets are also provided.
• Views, which provide subsitutions for templates. In PHP, these can be either associative arrays or objects.Member variables may be any valid PHP values, including callbacks; when callbacks are used, the return valuewill be substituted – which provides a mechanism for computing values, filtering them, etc.
This guide will take you through the basics of using the phly_mustache library, as well as provide a thoroughreference of the syntax supported, as well as implementation-specific features.
3
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
4 Chapter 1. phly_mustache
CHAPTER 2
Installation
2.1 Via Composer
1. Create a new file called composer.json and paste the following into it:
If you already have a composer.json file, just add this line to it.
2. Get composer if you don’t have it on your system from http://getcomposer.org
Then execute the following:
3. Usage
Once Composer has downloaded the component(s), all you need to do is include the vendor/autoload.php filethat was generated by Composer. This file takes care of autoloading all of the libraries so that you can use themimmediately:
2.2 Via a PSR-0 autoloader
phly_mustache follows the PSR-0 standard for class naming conventions, meaning any PSR-0-compliant classloader will work.
Refer to the docs of the autoloader you are using.
Examples are
Aura.Autoload Symfony Classloader Zend Framework Loader
2.3 Built-in autoloader
To simplify things out of the box, the component contains an _autoload.php file which will register an au-toloader for the phly_mustache component with spl_autoload. You can simply include that file, and startusing phly_mustache.
2.4 Instantiation
Usage is fairly straightforward:
5
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
include ’/path/to/library/Phly/Mustache/_autoload.php’;$mustache = new Phly\Mustache\Mustache();
Alternately, import the classes and/or namespaces you will use:
use Phly\Mustache\Mustache;$mustache = Mustache();
6 Chapter 2. Installation
CHAPTER 3
Usage
By default, phly_mustache will look under the current directory for templates ending with .mustache; you cancreate a stack of directories to search by using the setTemplatePath() method:
$mustache->setTemplatePath($path1)->setTemplatePath($path2);
In the above, it will search first $path2, then $path1 to resolve the template.
You may also change the suffix it will use to resolve templates:
$mustache = new Mustache();$mustache->setSuffix(’mst’); // now looks for files ending in ".mst"
7
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
8 Chapter 3. Usage
CHAPTER 4
Rendering
Rendering requires specifying a template and a view.
4.1 Overview: Templates and Views
A template may be either a string containing mustache markup, or a string referencing a mustache template file. Forsimplicity, the suffix of the file may be omitted, and a suffix will be appended; by default, this is ”.mustache”, but youmay also specify your own custom suffix.
Templates will typically provide placeholders for variables, using a double pair of braces (mustaches!) to enclose thevariable name:
Hello, {{name}}!
While additional syntax is available, this is the most basic concept to understand.
By default, variable values are escaped. This is to provide safe markup and reduce the chances of cross-site-scriptingattacks (XSS). If you know a value will be safe for output and/or do not want it escaped, surround the variable usingthree braces:
Hello, {{{name}}}!
A view is either an associative array or an object. In the case of an associative array, template variables will referencearray keys. In the case of an object, template variables may reference either a public property, or a public method.If a public method is referenced, or if the property value is a valid PHP callback, the return value from invoking themember will be returned.
The following are equivalent views:
$view = array(’name’ => ’Matthew’,’twitter’ => ’weierophinney’,
);
$view = new stdClass;$view->name = ’Matthew’;$view->twitter = ’weierophinney’;
class Matthew{
public $name = ’Matthew’;public function twitter(){
9
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
return ’weierophinney’;}
}$view = new Matthew();
While the last example is contrived, it does demonstrate that methods and properties are interchangeable.
Sometimes, you may want to create nested structures:
$view = array(’name’ => ’Matthew’,’contact’ => array(
’twitter’ => ’weierophinney’,’github’ => ’weierophinney’,
),);
Within your template, you can use “dot notation” to dereference such nested structures. Basically, a “dot” indicatesthat the preceding value should refer to an associative array or object, and that the segment following it should beretrieved:
The github user for {{name}} is {{contact.github}}.
The above will result in:
The github user for Matthew is weierophinney.
Now that you know about basic templating, variable substitution, and views, let’s look at how you actually renderusing phly_mustache.
4.2 Rendering String Templates
$test = $mustache->render(’Hello {{planet}}’,array(’planet’ => ’World’)
);echo $test;
which outputs as
Hello World
In the coming examples I will skip the echo statement to make the codes look small. We are also not using theopening <?php tags.
4.3 Rendering File Templates
Let the template be renders-file-templates.mustache in your templates folder. From here onwardswe assume you have your template in templates folder. Comments inside templates are marked between {{! and}}. Please note the character !.
{{!renders-file-templates.mustache}}Hello {{planet}}
Now you can render it
10 Chapter 4. Rendering
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
$test = $mustache->render(’renders-file-templates’, array(’planet’ => ’World’,
));
Outputs :
Hello World
4.4 Template Suffix
You may have noticed we have not added the suffix when we pass the template name. By default the suffix is ”.mus-tache”. However, you can change the suffix as desired; as an example, you might want to simply use ”.html”.
$mustache->setSuffix(’html’);$test = $mustache->render(’alternate-suffix’, array());
The above will look for the file alternate-suffix.html in your templates folder.
4.5 Rendering Object Properties
You are not limited to associative arrays for your views; you can also use objects, and phly_mustache will renderobject properties.
$view = new stdClass;$view->planet = ’World’;
$test = $mustache->render(’Hello {{planet}}’,$view
);
{{!render-object-properties.mustache}}{{content}}
$view = new stdClass;$view->content = ’This is the content’;$test = $mustache->render(’render-object-properties’, $view);
4.6 Rendering methods which return a value
Lets assume you have a class ViewWithMethod, and it contains a method taxed_value. If taxed_value isreferenced in the template, the return value of that method will be used.
class ViewWithMethod{
public $name = ’Chris’;public $value = 1000000;public $in_ca = true;
public function taxed_value(){
return $this->value - ($this->value * 0.4);
4.4. Template Suffix 11
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
}}
{{!template-with-method-substitution.mustache}}Hello {{name}}You have just won ${{taxed_value}}!
$chris = new ViewWithMethod();$test = $mustache->render(
’template-with-method-substitution’,$chris
);
Output :
Hello ChrisYou have just won $600000!
12 Chapter 4. Rendering
CHAPTER 5
Syntax
The following syntax is supported by phly_mustache.
5.1 Escaping
By default all variables assigned to a view are escaped.
$view = array(’foo’ => ’t&h\\e"s<e>’);$test = $mustache->render(
’{{foo}}’,$view
);
You will get characters escaped as below:
t&h\\e"s<e>
5.2 Prevent Escaping
You can prevent escaping characters by using triple brackets {{{
$view = array(’foo’ => ’t&h\\e"s<e>’);$test = $mustache->render(
’{{{foo}}}’,$view
);
This will output the same value you have given
Output :
t&h\\e"s<e>
5.3 Comments
Everyone needs to comment at some point or another. You can comment inside the delimeters {{! }}. Notice the ! .
13
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
{{!template-with-comments.mustache}}First line {{! this is a comment}}Second line{{! this isamultilinecomment}}Third line
When called:
$test = $mustache->render(’template-with-comments’, array());
It will render as:
First lineSecond line
Third line
5.4 Conditionals
Mustache tends to eschew logic within templates themselves. That said, simple conditionals are often necessary. Thesecan be accomplished using the {{#}}/{{/}} pair. Both tags will reference a variable in the view. If that variable ispresent and a truthy value, the content between the pair will be rendered; otherwise, it will be omitted. The contentmay contain arbitrary mustache markup, including references to variables.
{{!template-with-conditional.mustache}}Hello {{name}}You have just won ${{value}}!{{#in_ca}}Well, ${{taxed_value}}, after taxes.{{/in_ca}}
class Customer{
public $name = ’Chris’;public $value = 1000000;public $in_ca = true;
public function taxed_value(){
return $this->value - ($this->value * 0.4);}
}
$chris = new Customer;$test = $mustache->render(
’template-with-conditional’,$chris
);
Output:
Hello ChrisYou have just won $1000000!Well, $600000, after taxes.
14 Chapter 5. Syntax
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
With the following view object, we’ll get a different result:
class NonCalifornian extends Customer{
public $in_ca = false;}
$matthew = new NonCalifornian;$matthew->name = ’Matthew’;$test = $mustache->render(
’template-with-conditional’,$matthew
);
The above will result in:
Hello MatthewYou have just won $1000000!
This occurs because the $in_ca value is a non-truthy value; any value that would evalue to a boolean false (e.g., anull value, a zero integer or float, and empty string) when used in a conditional will be treated as if the value is notpresent, essentially skipping the conditional.
5.5 Iteration
While mustache tends to eschew logic, just as with conditionals, we may occasionally have repetitive data we need torender. Mustache provides functionality for iteration as well, using the concept of “sections”.
A section begins with a {{#}} token, and ends with a {{/}} token, and each references the variable within the view.The view variable is assumed to be iterable, with each item being another view (i.e., an associative array or an object).The tokens surround mustache content. Unlike conditionals, the assumption is that variables will dereference basedon the current item in the iteration. This may be better understood with an example. Given the following template:
{{!template-with-enumerable.mustache}}{{name}}:<ul>{{#items}}
<li>{{item}}</li>{{/items}}</ul>
We then have the following view:
class ViewWithArrayEnumerable{
public $name = "Joe’s shopping card";public $items = array(
array(’item’ => ’bananas’),array(’item’ => ’apples’),
);}
$view = ViewWithArrayEnumerable;$test = $mustache->render(
’template-with-enumerable’,$view
);
5.5. Iteration 15
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
This results in:
Joe’s shopping card:<ul>
<li>bananas</li><li>apples</li>
</ul>
As noted, the $items only needs to be iterable; it doesn’t have to be an array, it can be any Traversable object.
class ViewWithTraversableObject{
public $name = "Joe’s shopping card";public $items;
public function __construct(){
$this->items = new ArrayObject(array(array(’item’ => ’bananas’),array(’item’ => ’apples’),
));}
}
$view = new ViewWithTraversableObject;$test = $mustache->render(
’template-with-enumerable’,$view
);
The above will result in the exact same output as with the array example.
To take it a step further, each “item” could be an object:
class Item{
public $item;
public function __construct($item){
$this->item = $item;}
}
class ViewWithTraversableObject{
public $name = "Joe’s shopping card";public $items;
public function __construct(){
$this->items = new ArrayObject(array(new Item(’bananas’),new Item(’apples’),
));}
}
$view = new ViewWithTraversableObject;$test = $mustache->render(
16 Chapter 5. Syntax
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
’template-with-enumerable’,$view
);
5.6 Higher Order Sections Render Inside Out
Mustache has a concept of “higher order sections.”
In the previous section on iteration, we indicated that the {{#}}/{{/}} syntax indicates a section. While sectionscan be used for iteration, this is not their only use.
A higher order section is a variable that refers to a callable. In such a case, the mustache content for the section ispassed, as well as a reference to the mustache renderer, allowing the callable to return arbitrary content, and, if desired,render additional mustache content.
This is best illustrated with the following example.
class ViewWithHigherOrderSection{
public $name = ’Tater’;
public function bolder(){
return function($text, $renderer) {return ’<b>’ . call_user_func($renderer, $text) . ’</b>’;
};}
}
$view = new ViewWithHigherOrderSection();$test = $mustache->render(
’{{#bolder}}Hi {{name}}.{{/bolder}}’,$view
);
Output :
<b>Hi Tater.</b>
5.7 Rendering Nested Sections
In the previous sections on iteration and higher order sections, we indicated that the {{#}}/{{/}} syntax indicatesa section.
Another use for sections is for rendering hierarchical or nested data structures. When used in this way, the defaultscope within a section assumes that we are now within the scope of the dereference variable; as we go deeper in thenesting, we get into gradually more specific scope. Any given variable may contain another section, iterable content,higher order sections, or simply scalar output.
Let’s look at the following template:
{{!template-with-dereferencing.mustache}}{{#a}}
<h1>{{title}}</h1><p>{{description}}</p>
5.6. Higher Order Sections Render Inside Out 17
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
<ul>{{#list}}<li>{{label}}</li>{{/list}}
</ul>{{/a}}
And here’s a view that might be used with it:
$view = array(’a’ => array(
’title’ => ’this is an object’,’description’ => ’one of its attributes is a list’,’list’ => array(
array(’label’ => ’listitem1’),array(’label’ => ’listitem2’),
),),
);$test = $mustache->render(
’template-with-dereferencing’,$view
);
The generated output will resemble the following:
<h1>this is an object</h1><p>one of its attributes is a list</p><ul>
<li>listitem1</li><li>listitem2</li>
</ul>
5.8 Inverted Sections Render On Empty Values
{{!template-with-inverted-section.mustache}}{{#repo}}<b>{{name}}</b>{{/repo}}{{^repo}}No repos{{/repo}}
$view = array(’repo’ => array());$test = $mustache->render(
’template-with-inverted-section’,$view
);
Output :
No repos
5.9 Partials
Partials are a basic form of inclusion within Mustache; anytime you find you have re-usable bits of templates, movethem into a partial, and refer to the partial from the parent template.
Typically, you will only reference partials within your templates, using standard syntax:
18 Chapter 5. Syntax
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
{{>partial-name}}
However, you may optionally pass a list of partials when rendering. When you do so, the list should be a set ofalias/template pairs:
$mustache->render($template, array(), array(’winnings’ => ’user-winnings’,
));
In the above example, ‘winnings’ refers to the template “user-winnings.mustache”. Thus, within the $template beingrendered, you may refer to the following partial:
{{>winnings}}
and it will resolve to the appropriate aliased template.
A few things to remember when using partials:
The parent template may change tag delimiters, but if you want to use the same delimiters in your partial, you willneed to make the same declaration. The parent template may utilize one or more pragmas, but those declarations willnot perist to the partial; if you want those pragmas, you must reference them in your partial. Basically, partials renderin their own scope. If you remember that one rule, you should have no problems.
{{!template-with-partial.mustache}}Welcome, {{name}}! {{>partial-template}}
{{!partial-template.mustache}}You just won ${{value}} (which is ${{taxed_value}} after tax)
class ViewWithObjectForPartial{
public $name = ’Joe’;public $winnings;public $value = 1000;public function taxed_value(){
return $this->value - ($this->value * 0.4);}
}
$view = new ViewWithObjectForPartial();$test = $mustache->render(
’template-with-partial’,$view
);
Output :
Welcome, Joe! You just won $1000 (which is $600 after tax)
5.10 Aliasing Partials
{{!partial-template.mustache}}You just won ${{value}} (which is ${{taxed_value}} after tax)
{{!template-with-aliased-partial.mustache}}Welcome, {{name}}! {{>winnings}}
5.10. Aliasing Partials 19
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
$view = ViewWithObjectForPartial();$test = $mustache->render(
’template-with-aliased-partial’,$view,array(’winnings’ => ’partial-template’)
);
Output:
Welcome, Joe! You just won $1000 (which is $600 after tax)
5.11 Alternate Delimiters
You can specify alternate delimiters other than {{ and }} . This is possible via adding new deliminiter inside {{=<%%>=}} Assuming the <% and %> is new delimiter.
{{!template-with-delim-set.mustache}}{{=<% %>=}}This is content, <%substitution%>, from new delimiters.
$test = $mustache->render(’template-with-delim-set’, array(’substitution’ => ’working’));
Output :
This is content, working, from new delimiters.
5.12 Alternate Delimiters in selected areas only
Sometimes you may want alternative delimiter in selected areas. Its also possible adding it inside {{#section}} and{{/section}}
{{!template-with-delim-set-in-section.mustache}}Some text with {{content}}{{#section}}{{=<% %>=}}
<%name%>{{/section}}{{postcontent}}
$test = $mustache->render(’template-with-delim-set-in-section’, array(’content’ => ’style’,’section’ => array(
’name’ => ’-World’,),’postcontent’ => ’P.S. Done’,
));
Output :
Some text with style-World
P.S. Done
20 Chapter 5. Syntax
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
5.13 Alternate Delimiters Apply To Child Sections
You can apply alternate delimiters to child via substitution
{{!template-with-sections-and-delim-set.mustache}}{{=<% %>=}}Some text with <%content%><%#substitution%>
<%name%><%/substitution%>
$test = $mustache->render(’template-with-sections-and-delim-set’,array(’content’ => ’style’, ’substitution’ => array(’name’ => ’-World’))
);
Output :
Some text with style-World
Partials don’t have any effect on alternative delimiters.
{{!partial-template.mustache}}You just won ${{value}} (which is ${{taxed_value}} after tax)
{{!template-with-partials-and-delim-set.mustache}}{{=<% %>=}}This is content, <%substitution%>, from new delimiters.<%>partial-template%>
$test = $mustache->render(’template-with-partials-and-delim-set’, array(’substitution’ => ’style’,’value’ => 1000000,’taxed_value’ => 400000,
));
Output :
This is content, style, from new delimiters.You just won $1000000 (which is $400000 after tax)
5.14 Recursive Partials
Partials can be used recursively
{{!crazy_recursive.mustache}}<html><body><ul>
{{#top_nodes}}{{> node}}
{{/top_nodes}}</ul></body></html>
{{!node.mustache}}
5.13. Alternate Delimiters Apply To Child Sections 21
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
<li>{{contents}}<ul>
{{#children}}{{>node}}
{{/children}}</ul>
</li>
$view = array(’top_nodes’ => array(
’contents’ => ’1’,’children’ => array(
array(’contents’ => ’2’,’children’ => array(
array(’contents’ => 3,’children’ => array(),
)),
),array(
’contents’ => ’4’,’children’ => array(
array(’contents’ => ’5’,’children’ => array(
array(’contents’ => ’6’,’children’ => array(),
),),
),),
),),
),);$test = $mustache->render(’crazy_recursive’, $view);
Try yourself to see the rendering :)
5.15 PHP functions will not work inside templates
{{!template-referencing-php-function.mustache}}{{message}}
template-referencing-static-function-notempty.mustache{{#message}}{{message}}{{/message}}
$test = $mustache->render(’template-referencing-php-function’, array(’message’ => ’time’,
));
22 Chapter 5. Syntax
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
$model = (object) array(’message’ => ’time’);$test = $mustache->render(’template-referencing-php-function’, $model);
$model = array(’message’ => ’DateTime::createFromFormat’);$test = $mustache->render(’template-referencing-php-function’, $model);
$model = array(’message’ => ’time’);$mustache->getRenderer()->addPragma(new ImplicitIterator());$test = $mustache->render(’template-referencing-static-function-notempty’, $model);
$model = array(’section’ => array(’DateTime’, ’createFromFormat’));$mustache->getRenderer()->addPragma(new ImplicitIterator());$test = $mustache->render(’template-referencing-static-function’, $model);
5.16 Hierarchical / Template Inheritance
Hierarchical Views and Placeholders (Available in versions 1.1.0 and up).
Placeholders are basically unnamed sections, and are denoted by the combination of {{$name}} and {{/name}}.When encountered by the renderer, any mustache content within will be rendered as normal mustache content.
Placeholders are primarily of use with the concept of hierarchical views. These are denoted by the combination of{{<name}} and {{/name}}. When encountered, the template denoted by name will be tokenized, and any placeholdersthat are defined in the content will be used to replace those found in the parent template.
As an example, consider the following parent template, “super.mustache”:
{{!super.mustache}}<html><head><title>{{$title}}Default title{{/title}}</title></head><body>{{>navigation}}<div class="content">{{$content}}Default content of the page{{/content}}</div>{{>footer}}</body></html>
{{!navigation.mustache}}<nav><a href="/">Home</a> | <a href="/blog">Blog</a></nav>
{{!footer.mustache}}<footer>End of page</footer>
If rendered by itself, it will result in the following:
<html><head><title>Default title</title></head><body><nav><a href="/">Home</a> | <a href="/blog">Blog</a></nav><div class="content">Default content of the page</div><footer>
5.16. Hierarchical / Template Inheritance 23
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
End of page</footer></body></html>
Now, consider the following child template, “sub.mustache”:
{{!sub.mustache}}{{<super}}{{$title}}Profile of {{username}} | Twitter{{/title}}{{$content}}Here is {{username}}’s profile page{{/content}}{{/super}}
If we have a view that defines “username” as “Matthew” and render “sub.mustache”,
$view = new stdClass;$view->username = ’Matthew’;$test = $mustache->render(’sub’, $view);
we’ll get the following:
<html><head><title>Profile of Matthew</title></head><body><nav><a href="/">Home</a> | <a href="/blog">Blog</a></nav><div class="content">Here is Matthew’s profile page</div><footer>End of page</footer></body></html>
Notice how the child retains the view context of the parent, and that all mustache tokens defined in it are rendered asif they were simply another mustache template.
Hierarchical templates may be nested arbitrarily deep.
24 Chapter 5. Syntax
CHAPTER 6
Pragmas
Pragmas are a way to extend the mustache syntax, as well as alter it.
(More here... including list of those shipped, and examples of using the various pragmas shipped.)
6.1 Pragmas Are Section Specific
Lets take the Implicit Iterator defined in one section.
{{!template-with-pragma-in-section.mustache}}Some content, with {{type}}{{#section1}}{{%IMPLICIT-ITERATOR}}
{{#subsection}}{{.}}
{{/subsection}}{{/section1}}{{#section2}}
{{#subsection}}{{.}}
{{/subsection}}{{/section2}}
You can see its only in section1.
$mustache->getRenderer()->addPragma(new Phly\Mustache\Pragma\ImplicitIterator());$test = $mustache->render(’template-with-pragma-in-section’, array(
’type’ => ’style’,’section1’ => array(
’subsection’ => array(1, 2, 3),),’section2’ => array(
’subsection’ => array(4, 5, 6),),
));
The contents of section1.subsection will be iterated. But not that of section2.subsection.
Output :
Some content, with style
1
25
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
23
6.2 Pragmas Do Not Extend To Partials
{{!partial-with-section.mustache}}This is from the partial{{#section}}
{{#subsection}}{{.}}
{{/subsection}}{{/section}}
{{!template-with-pragma-and-partial.mustache}}{{%IMPLICIT-ITERATOR}}Some content, with {{type}}{{>partial-with-section}}
$mustache->getRenderer()->addPragma(new Phly\Mustache\Pragma\ImplicitIterator());$test = $mustache->render(’template-with-pragma-and-partial’, array(
’type’ => ’style’,’section’ => array(
’subsection’ => array(1, 2, 3),),
));
Output :
Some content, with style
This is from the partial
6.3 Implicit Iterator
{{!template-with-implicit-iterator.mustache}}{{%IMPLICIT-ITERATOR iterator=bob}}{{#foo}}
{{bob}}{{/foo}}
$mustache->getRenderer()->addPragma(new Phly\Mustache\Pragma\ImplicitIterator());$view = array(’foo’ => array(1, 2, 3, 4, 5, ’french’));$test = $mustache->render(
’template-with-implicit-iterator’,$view
);
Output :
1234
26 Chapter 6. Pragmas
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
5french
6.3. Implicit Iterator 27
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
28 Chapter 6. Pragmas
CHAPTER 7
Resolvers
Resolvers are a feature specific to Phly\Mustache‘s implementation. What a resolver does is accept a templatename, and return either the Mustache content, or a set of tokens that Phly\Mustache understands.
7.1 The ResolverInterface
All resolvers simply implement Phly\Mustache\Resolver\ResolverInterface, which looks like this:
namespace Phly\Mustache\Resolver;
interface ResolverInterface{
/*** Resolve a template name
** Resolve a template name to mustache content or a set of tokens.
** @param string $template
* @return string|array\*/
public function resolve($template);}
You can attach a ResolverInterface implementation to the Mustache instance, using the setResolver()method:
$mustache->setResolver($resolver);
At that point, that resolver will be used. If a resolver returns a boolean false value, Mustache will raise aTemplateNotFoundException.
To access the current resolver – for example, to manipulate its state or set configuration – you can retrieve it from theMustache instance as well:
$resolver = $mustache->getResolver();
7.2 The DefaultResolver
Phly\Mustache comes with one resolver, Phly\Mustache\Resolver\DefaultResolver. This imple-mentation is a filesystem-based implementation, and looks for a template within an internal stack of templates. If
29
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
found, it returns the content of that template.
It has three features you can manipulate:
• Filesystem directory separator, via setSeparator().
• File suffix, via setSuffix().
• Template path stack, via setTemplatePath()‘ and ‘‘clearTemplatePath() (the latter removesall paths from the stack).
As this is the default implementation, the setSuffix() and setTemplatePath() methods have proxy methodsin the main Mustache class as well.
One interesting use case for manipulating the filesystem directory separator is to allow using “dot notation” for tem-plate names, and having each segment map to a directory:
$mustache->getResolver()->setSeparator(’.’);
// Render foo/bar.mustache:echo $mustache->render(’foo.bar’);
7.3 Use Cases
As the DefaultResolver provides a reasonable default, what other uses exist for resolvers? Potential reasons foralternate implementations include:
• Caching resolvers. A resolver could pull from the filesystem on first invocation, but then cache any compiledtokens when complete.
• Database-backed resolvers. Store templates in a relational or document database.
Basically, resolvers provide a convenient extension point for providing Mustache template content and/or tokens tothe system.
30 Chapter 7. Resolvers
CHAPTER 8
Api docs:
API docs are available.
31
Phly\Mustache - Mustache Implementation in PHP 5.3 Documentation, Release 1.2.0dev
32 Chapter 8. Api docs:
CHAPTER 9
Indices and tables
• genindex
• modindex
• search
33