I'm looking to get started with Twig, but having a real headache getting the {% block %} to work at all - I feel there must be something very obvious I am missing.
My index.php loader looks as follows:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once( "Twig/Autoloader.inc.php" );
Twig_Autoloader::register();
$twig = new Twig_Environment( new Twig_Loader_Filesystem("templates"));
$vars = array (
"user" => array(
"name" => "Joe Bloggs"
),
"title" => "My website"
);
$tpl = $twig->loadTemplate("index.html");
echo $tpl->render($vars);
?>
A simplified version of the index.html in /templates
looks like this:
<!doctype html>
<html>
<body>
Hello World!
{% block navigation %}Test{% endblock %}
</body>
</html>
And the navigation.html in /templates
looks something like this:
{% extends "index.html" %}
{% block navigation %}
<!-- Navigation -->
<nav>
Some navigation
</nav>
{% endblock %}
So far as I understood it, this should be a basic working example of the blocks feature. The other aspects of Twig seem to be working just fine for me, and no errors are being reported. Indeed, the page successfully prints "Test".
Should I be explicitly pointing to the navigation.html file somewhere, or does Twig automatically load all the files in the /templates
folder?
The error: you're rendering your index template instead of the navigation one.
In the index template, the navigation block contains "Test", so your output is correct. If you render navigation.html, you'll get your html content from index.html and the navigation block from the navigation template (the only thing it overrides).
You always need to render the template you wish to output. One may be extended by many (for example, your layout may be extended by all your actions' templates).