Tutorial

How To Install and Get Started with Twig on a VPS

Published on September 11, 2013
How To Install and Get Started with Twig on a VPS

About Twig

Twig is a modern template engine designed for PHP that is both designer and developer friendly. It is a very good alternative to the PHPTemplate way of building the presentation logic of a web application as it represents a much cleaner templating experience. In this respect, it comes with a very easy to understand syntax and restricts you from performing dynamic PHP operations in template filess, which you shouldn't be doing.

If you like to use PHP frameworks for building web applications, you should check out Symfony2 as it comes with Twig installed by default. There are a couple of tutorials on this website about installing and using Symfony2, so you can go ahead and check them out as well.

In this tutorial we will look at how to install Twig on a VPS and get started with it. For this, we assume you are already running your own cloud server, preferably Linux-based. We will go with the LAMP stack already installed, although the database will not really be used in this tutorial. Twig requires PHP 5.2.4 or higher to run and you should be fine also with other web servers than Apache.

Why Twig?

Or why any templating engine? Very simple: separation of concerns. Let’s demonstrate by first creating a project folder in our web server’s document root (/var/www) called twig:

cd /var/www
mkdir twig
cd twig

Add a couple of folders for our tiny application: one for the php files and one for our Twig template files (respectively):

mkdir app
mkdir views

Inside the app folder, create a php file:

nano app/app.php

Into which, let’s paste the following code meant to output Hello World onto the page:

<?php echo "<h1>Hello world!</h1>" ?>

Save the file and point your browser to this file. If you followed along this would be at your-ip-address/twig/app/app.php. You should see the statement printed out correctly within the H1 tag.

Now what is wrong with this approach? If this PHP file becomes much more complex (and it will for any application), you will have a big problem with managing the layout of your site. We just hardcoded the H1 tag into the PHP echo statement which is a bad thing. If you want a designer to work with it, this designer will have to search into this file which is what we want to prevent. So the solution is the separation of the presentation (layout) from the logic (programming) and the best way to do it is by using a template engine such as Twig. We’ll come back to our tiny app after we install Twig.

Installation

The recommended way to install Twig is via Composer, the PHP dependency management tool. If you don’t know what this is, there is another tutorial you can check out for more information. But don’t worry, it’s not a big deal, as you will see in a moment.

Let’s download the Composer installer into our application’s root folder (twig):

cd /var/www/twig
curl -s http://getcomposer.org/installer | php

This should download a single file called composer.phar which is the Composer executable. Next up, create a file called composer.json right next to it:

nano composer.json

And paste the following lines into it:

{
    "require": {
        "twig/twig": "1.*"
    }
}

This makes our application dependent on the Twig templating engine. Now let’s use the composer command to install the dependencies:

php composer.phar install

The Twig files are downloaded into the vendor/Twig folder. If you add other dependencies, they will also be installed in the vendor folder.

Now we need to "connect" it to our application. Since we used Composer, we can use it’s autoloader functionality to load all the dependencies we installed. So let’s open our app.php file:

nano app/app.php 

Remove everything inside and add this line to the top:

<?php require_once '../vendor/autoload.php'; ?>

With this line, we load the Composer autoloader which in turn loads Twig. If you installed Twig some other way, you’ll have to require the Twig autoloader directly:

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

But we don’t need to do this with Composer. Below the require statement we just wrote, we need to locate a Twig template file and pass it the variable we want printed out to the page. Paste the following code:

<?php $loader = new Twig_Loader_Filesystem('../views/'); ?>

<?php $twig = new Twig_Environment($loader); ?>

<?php echo $twig->render('page.html', array('text' => 'Hello world!')); ?>

What does this do right here? First, we create a loader object to which we pass the path to the folder that contains our template files (the views folder we created earlier which currently is empty). Next, we create an environment object that stores configuration. And lastly, the most interesting part, the render method of the environment object loads the template file passed as the first argument and renders it with variables passed as the second argument. So we will now need to create the page.html file and inside we will have a variable available that contains the statement we want printed out. So let’s do just that:

nano views/page.html

And inside, paste the following:

<h1>{{ text }}</h1>

If you save the file and reload the app.php file in the browser, you should get the same text printed in between the H1 tags. But now, we have this separate file we can play around to display it however we want. And the variables we passed through the render function are now available to be printed in between the double curly braces.

So you can go ahead and play around with this file and experiment on your own. You can pass multiple variables to the template, use them in control structures, process them through templating functions or even apply Twig filters

Conclusion

In this tutorial we saw how to install Twig with Composer and how to get started printing out simple variables on a page using separate template files. In the next tutorial we will go a bit deeper into using the Twig syntax to build your template files.

Article Submitted by: Danny

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: Introduction to Twig

Twig is a flexible, fast, and secure template engine for PHP. This series covers the basics of Twig installation, setup, and usage.

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
4 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I am confused in the part about why Twig is useful where you say you need to run <?php echo “<h1>Hello world!</h1>” ?>. You do realize you can just put <h1>Hello world!</h1> in a php file without echo, or any php tags whatsoever, don’t you?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 7, 2014

@jonathan: You’re correct – I’ve updated part 2 of the series to use .displayShape() instead of .shape(). Thanks!

Just one little error I think I found - unless I am doing something wrong, but I copied and pasted and I think:

If we want the return of the displayShape() method, we do this:

{{ myBox.shape() }}

should be

{{ myBox.displayShape() }}

Or, at least, it doesn’t work for me unless I change it like that :)

Hi there; I just wanted to thank you very much for writing these two tutorials. I’d looked at Twig before but never found a good quick start guide which gave such a clear and concise overview. Got me up and Twigging in under 10 minutes! Many thanks!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.