<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ryan&#039;s Blog &#187; Twig</title>
	<atom:link href="http://www.rmauger.co.uk/topics/twig/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rmauger.co.uk</link>
	<description>Randomness will get you everywhere.</description>
	<lastBuildDate>Mon, 06 May 2013 14:09:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Using Twig with Zend Framework</title>
		<link>http://www.rmauger.co.uk/2011/05/using-twig-with-zend-framework/</link>
		<comments>http://www.rmauger.co.uk/2011/05/using-twig-with-zend-framework/#comments</comments>
		<pubDate>Wed, 04 May 2011 21:07:34 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Content Management]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Twig]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[templating system]]></category>
		<category><![CDATA[twig]]></category>
		<category><![CDATA[zf]]></category>

		<guid isPermaLink="false">http://www.rmauger.co.uk/?p=177</guid>
		<description><![CDATA[Twig, in short, is a templating system for PHP. But PHP is already a templating system many would argue! Well, I wouldn&#8217;t argue against that point. However, with the recent excitement in the air in the PHP Community about Symfony 2, I thought it worth checking out. Mostly I thought they were silly things that [...]]]></description>
				<content:encoded><![CDATA[<p>Twig, in short, is a templating system for PHP. But PHP is already a templating system many would argue! Well, I wouldn&#8217;t argue against that point. However, with the recent excitement in the air in the PHP Community about Symfony 2, I thought it worth checking out.<br />
Mostly I thought they were silly things that were not really needed unless you had a team of designers to work with, however, during my exploration, a couple of things occurred to me that I had not considered about templating systems before. One being the enforced separation of concerns they provide; you simply cannot do anything from inside them which you shouldn&#8217;t be, keeping your presentation very very clean. The second, being that they&#8217;re not all as terrible as Smarty.</p>
<p><span id="more-177"></span></p>
<h2>Installing Twig</h2>
<p>This really couldn&#8217;t get a lot simpler with pear:</p>
<pre>    $ pear channel-discover pear.twig-project.org
    $ pear install twig/Twig</pre>
<p>or, you can use the Git or Subversion repos as detailed on the projects website: <a href="http://www.twig-project.org/doc/intro.html">http://www.twig-project.org/doc/intro.html</a></p>
<p><strong>The Application Resource</strong></p>
<p>Setting up a ZF application resource for twig is a snip! The minimal config required to set up a Twig instance, is exactly that, minimal!</p>
<p>Simple create the class &#8220;Core_Resource_Twig&#8221; and place it in library/Core/Resource/Twig.php and consider the following code:</p>
<pre>&lt;?php

class Core_Resource_Twig extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * @var Twig_Environment
     */
    protected $twig;

    public function init()
    {
        $options = $this-&gt;getOptions();
        $loader = new Twig_Loader_Filesystem($options['templateDir']);
        $this-&gt;twig = new Twig_Environment(
                $loader,
                $options['options']
        );
        return $this-&gt;twig;
    }
}</pre>
<p>All we are doing here, is creating an instance of the Filesystem Twig loader, which loads templates from files, and then passing that in to the Twig Environment, along with the rest of the options from our config, which in brief, would now look something like this:</p>
<pre>
[production]
autoloaderNamespaces[] = "Twig_"
pluginPaths.Core_Resource = APPLICATION_PATH "/../library/Core/Resource"

; FRONT CONTROLLER
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.controllerDirectory.default = APPLICATION_PATH "/controllers"
resources.frontController.noViewRenderer = true

; TWIG
resources.twig.templateDir = APPLICATION_PATH "/templates"
resources.twig.options.cache = APPLICATION_PATH "/../cache/twig"

[development : production]
resources.twig.options.debug = true
resources.twig.options.auto_reload = true
</pre>
<p>That now gives us two things, a configured Twig instance, and an application resource to hold it, which will be present in the invoke args in your controller. so for the next step, we stitch it together, and make it more useable, to make things super simple, a base controller class is useful here. The reason for a base controller class rather than an action helper is simple, performance, and simplicity; no need for the complexity or auto-rendering anything, we will simply call a method at the end of each action.</p>
<p>Given that we are now using twig, this has two benefits, we avoid the overhead of how ZF looks up the view name to decide which view template to render, which is a part of the bottleneck of ZF, and additionally, it matches more closely to the other documentation you&#8217;ll find on Twig elsewhere, and we are doing things in a slightly different manner to how we would use Zend_View, so why try to emulate it, when we are using something very different!</p>
<pre>&lt;?php

abstract class Core_Controller extends Zend_Controller_Action
{
    public function twig($template, array $vars)
    {
        $twig = $this-&gt;getBootstrap()-&gt;getResource('twig');

        $template = $twig-&gt;loadTemplate($template);
        $this-&gt;getResponse()-&gt;appendBody(
            $template-&gt;render($vars),
            'default'
        );
    }
}</pre>
<h2>Rendering the template</h2>
<p>Now that we have our base controller class, we can now use our template, in this manner from our action:</p>
<pre>&lt;?php

class IndexController extends Core_Controller
{
    /**
     * @var Core_Service_Posts
     */
    protected $service;

    public function init()
    {
        $this-&gt;service = new Core_Service_Posts();
    }

    public function indexAction()
    {
        $recent = $this-&gt;service-&gt;recentPosts();
        $this-&gt;twig('home.twig', array(
            'recent' =&gt; $recent,
        ));
    }

    public function viewAction()
    {
        $id = $this-&gt;getRequest()-&gt;getParam('id', false);
        if (false === $id) {
            throw new Core_InvalidIdException('No ID Present');
        }

        $paste = $this-&gt;service-&gt;byId($id);

        $this-&gt;twig('view-post.twig', array(
            'post' =&gt; $paste,
        ));
    }

}</pre>
<p>In this example, you have the indexAction, taking the service for the posts for the application, and passing the recent posts to the template, and in the view action, taking the selected post, and passes it to the template, with the selection of template for the action being passed as the first argument to our twig method we added to the base controller class.</p>
<p>And now, you can find examples and documentation on how to put together your twig templates here <a href="http://www.twig-project.org/documentation">http://www.twig-project.org/documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rmauger.co.uk/2011/05/using-twig-with-zend-framework/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
