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 }}
I figured out when you're calling a template, you're able to call two. So for example, the follow code will pass the variables into both index.tmpl and menu.tmpl
$template = $twig->loadTemplate('index.tmpl', 'menu.tmpl');
I needed to do this because index.tmpl was my main page as to keep the entire sites template intact, I also needed to pass two variables to menu.tmpl. Before, I included my menu file, menu.inc.php' into the pages but that became broken after a while. What I changed was that I added Twig variables to menu.tmpl, which changes on whether a user is logged in. So, rather than using menu.inc.php anymore, I went to the template.
To include templates is simple:
{% include 'menu.tmpl' %}
Also, one could also extend one template with another. There are no foreach or while loops available in Twig but you can use this as a foreach statement:
{% for message,thing in test %} {{ message }} contains {{ thing }} {% endfor %}
Twig also has a sandbox feature which seems great for sanitizing input and such. I'm definitely glad I found out about Twig; my code is much cleaner and doesn't look [as ] hideous.