PHP Twig Template Wrapper

May 2, 2011 No comments yet

Requirements

Template Class

The use of the Settings class is self explanatory. Just replaces the instances of Settings with your own configuration system (or just strings). All Twig settings are documented here.

class Template
{

	public $context = array();

	private $template;

	public function __construct($template)
	{		

		$loader = new Twig_Loader_Filesystem(Settings::get('template_directories'));

		$twig = new Twig_Environment($loader, array(

			'cache' => Settings::get('template_cache_directory'),
			'debug' => Settings::get('debug'),

				)

		);

		$this->template = $twig->loadTemplate($template);

	}

	public function setContext(array $context = array())
	{
		$this->context = array_merge($context, $this->context);

	}

	public function render()
	{
		return $this->template->render($this->context);
	}	

	public function __toString()
	{
		return $this->render();
	}

	public function __set($key, $val)
	{
		$this->context[$key] = $val;
	}

	public function __get($key)
	{
		return $this->context[$key];
	}

}

Simple Example

hello.html

Hey there <strong>{{ name }}</strong> welcome to the website.

Code in controller

$t = new Template('hello.html');
$t->name = 'Frank';
echo $t->render();

Output:

Hey there <strong>Frank</strong> welcome to the website.

Example with Inheritance

base.html

<h3>Welcome to the website<h3>
{% block content %}{% endblock %}

hello.html

{% extends 'base.html' %}
{% block content %}
Hey there <strong>{{ name }}</strong> welcome to the website.
{% endblock %}

Code in controller

$t = new Template('hello.html');
$t->name = 'Joe';
echo $t->render();

Output:

Writing a module for Kohana3

December 20, 2010 No comments yet

In this tutorial we will cover how to build a module from scratch in Kohana 3. If you aren’t familiar with the Kohana framework then I recommend you read the beginners introduction to Kohana.

The Plan

We will be building a module that replaces Kohana’s own view layer (Kohana_View). It will use the PHP template library Twig. We want our own view layer to be API compatible with Kohana’s view layer. This will ensure that other modules work out of the box and that the only code the developer will need to alter in their application are the templates (so that they are Twig compatible). No code in any controller will need to be modified.

Because Kohana follows HMVC (see beginners introduction to Kohana) we will be calling our class View. This means that all calls in the application to the class of View will be to the View class in our module, not Kohana’s own View class.

Directory Structure

Enabling The Module

The name of any Kohana module is the same name as the directory inside the modules directory. So in this case it is twig. To activate any module, we must add it…