Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Twig is most commonly installed using Composer. It can be installed as its own package in a standalone project, or many frameworks allow you to choose Twig as your preferred templating engine. Sometimes frameworks may have specific packages to better communicate with Twig.
Twig Documentation
Installing Twig as a Standalone
The recommended way to install Twig is via Composer:
composer require "twig/twig:^2.0"
Basic API Usage
This section gives you a brief introduction to the PHP API for Twig.
<?php
require_once '/path/to/vendor/autoload.php';
$loader = new Twig_Loader_Array([
'index' => 'Hello {{ name }}!',
]);
$twig = new Twig_Environment($loader);
echo $twig->render('index', ['name' => 'Fabien'])
Installing Twig with Slim
The slim/twig-view component allows you to render Twig templates instead of PHP templates in your application.
Step 1: Install slim/twig-view. The easiest way is through composer.
composer require slim/twig-view
Step 2: Next, you need to change the registered view component on the Slim app’s container like this:
// Get container
$container = $app->getContainer();
// Register component on container (your view or renderer)
$container['view'] = function ($c) {
$settings = $c->get('settings')['renderer'];
$view = new \Slim\Views\Twig($settings['template_path']);
return $view;
};
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up