shit

Templating with Twig

I've been working on this shitty video sharing site for a couple weeks now and thought I'd try out some new things. I' used phpass for the password management and ended up using Twig as a template framework. I've never used a template engine before so I was new to using one. Twig is actually quite easy to implement into any of your projects. In your PHP script add:

 

require_once 'Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);
$template = $twig->loadTemplate('index.html');
echo $template->render(array('value' => 'test');

And that's it. In the example, 'index.html' is the template file. The array passes the variables onto the template. So, your index.html would look something like this:

 

This is a {{ value }} 

That would echo 'test'. The documentation for Twig is alright but it doesn't show how one uses the core extensions. See the below example as a block is transated for Twig's use:

 

      $a = $s + ($limit);
       if ($a > $numrows):
       $a = $numrows;
       endif;
       $b = $s + 1;
       echo "Showing results $b to $a of $numrows";

Becomes:

{% set a = s + limit %}
    {% if a > numrows %}
        {% set a = numrows %}
    {% endif %}    
{% set b = s + 1 %}  
   Showing results {{ b }} to {{ a }} of  {{ numrows }}