Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Twig: The Basics

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

Welcome to the world of Twig! Twig is a templating language for PHP, which is a boring way of saying that it's a tool used to output variables inside HTML. If a project you're working on uses Twig, then you're in luck: it's easy to learn, powerful and a joy to work with.

To make this interesting, let's build something useful with Twig like a penguin clothing store! Actually, I've already got us started. I have a small website setup under my web server's document root and a test page called test.php.


Want to run this code locally? Download the code from this page, then following the directions in the README.md file inside.

Right now, this file prepares some pageTitle and products variables and then includes another file:

// test.php

// setup some variables
$pageTitle = 'Suit Up!';
$products = array(
    new Product('Serious Businessman', 'formal.png'),
    new Product('Penguin Dress', 'dress.png'),
    new Product('Sportstar Penguin', 'sports.png'),
    new Product('Angel Costume', 'angel-costume.png'),
    new Product('Penguin Accessories', 'swatter.png'),
    new Product('Super Cool Penguin', 'super-cool.png'),

// render out PHP template
include __DIR__.'/templates/homepage.php';

The homepage.php file is the actual template. It has all the HTML and we use foreach to loop through them and then echo to print out some variables:

<!-- templates/homepage.php -->

<!-- ... the rest of the HTML page ... -->
<?php foreach ($products as $product) : ?>
    <div class="span4">
        <h2><?php echo $product->getName() ?></h2>
        <!-- ... -->
<?php endforeach; ?>

Instead of using PHP, let's write our template using Twig! The goal of the template is still the same: to print out variables. The only thing that will change is the syntax.

Setting up Twig

In a separate file, I've setup all the behind-the-scenes work to use Twig. Let's start by rendering a homepage.twig file and once again passing it pageTitle and products variables:

// index.php
// ... code that sets up Twig, and says to look for templates in template/

echo $twig->render('homepage.twig', array(
    'pageTitle' => 'Welcome to Penguins R Us!',
    'products' => array(
        'Bow tie',
        'Black Boxers',

If you're curious how you actually setup Twig, check out the code download and see the Twig Installation documentation.

If you're a frontend developer, then you don't need to worry about this step: all you need to know is where a Twig template is located and what variables you have access to.

Your first Twig Template

In our project, Twig is looking for the template files in a templates/ directory, so let's create our homepage.twig there!

Just like in PHP, you can write anything and it'll just be displayed as HTML on the page:

<!-- templates/homepage.twig -->
Hello Twig Viewers!

To see this amazing message, go to the index.php file in your browser. This works because we made the index.php file render the homepage.twig template. Whenever you're creating or editing a page, you'll need to figure out which Twig template is being used for that page. There's no exact science to this and it depends on how your application is built.

Rendering a Variable

Remember that we're passing a pageTitle variable to our template. To render it, write two opening curly braces, the name of the variable without a dollar sign, then two closing curly braces:

<!-- templates/homepage.twig -->
<h1>{{ pageTitle }}</h1>

When we refresh the page, it works! We've just written our first line of Twig! Whenever you want to print something, just open Twig with two curly braces, write the variable name, then close Twig. We'll get fancier in a little while with some things called functions and filters, but this is the most fundamental syntax in Twig.

Looping over Variables

Next, the products variable is an array that we need to loop through. Twig comes with a for tag that is able to loop through items just like PHP's foreach.

Remember that anything we type here will be printed out raw on the page until we "open up" Twig. This time, open Twig by typing {%. Now that we're in Twig, use the for tag to loop over products. product will be the variable name we use for each item as we loop. Close Twig by adding an identical %}. Unlike when we echo'ed the pageTitle variable, the for tag needs an endfor:

<!-- templates/homepage.twig -->
<h1>{{ pageTitle }}</h1>

<div class="row">
    {% for product in products %}

    {% endfor %}

Twig will loop over each item in products and execute each line between for and endfor. Each item in products is just a string, so let's print it out:

<!-- templates/homepage.twig -->
<h1>{{ pageTitle }}</h1>

<div class="row">
    {% for product in products %}
        <div class="span4">
            <h2>{{ product }}</h2>
    {% endfor %}

This works exactly like before. We have a product variable, so we can print it by placing it inside two opening curly braces and two closing curly braces.

And when we refresh, another Twig success! Before long, we'll have these penguins looking fly.

The 2 Syntaxes of Twig: {{ and {%

So we've seen how to print a variable and how to loop over a variable that's an array or collection. This may not seem like much, but you've already seen pretty much all of Twig's syntaxes! To start writing Twig code in your HTML, there are only two different syntaxes:

The "Say Something" Syntax: {{ ... }}

The double-curly-brace ({{) is always used to print something. If whatever you need to do will result in something being printed to the screen, then you'll use this syntax. I call this the "say something" tag, ya know, because it's how you "speak" in Twig.

The "Do Something" Syntax: {% ... %}

The curly-percent ({%) is the other syntax, which I call the "do something" syntax. It's used for things like if and for tags as well as other things that "do" something. The {% is really easy because there are only a handful of things that can be used inside of it. If you go to Twig's website click Documentation, and scroll down, you can see a full list of everything in Twig. The "tags" header shows you everything that can be used inside of a "do something" tag, with more details about how each of these works. The only ones you need to worry about now are if and for. We'll talk about a bunch more of these later.

And that's it! Use the {{ "say something" syntax to print and the {% "do something" when you want to do one of the things on this list. These are the only two Twig syntaxes and we'll learn more tools that can be used inside of each of these.

The Comment Syntax: {# ... #}

Actually, we've lied a little. There is a third syntax, used for comments: {#. Just like with the "say something" and "do something" syntaxes, write the opening {# and also the closing #} at the end of your comments:

{# This template is really starting to get interesting ... #}
{# ... #}


We'll use the {# ... #} syntax in the rest of this tutorial whenever we're hiding some parts of a Twig template.

Whitespace inside Twig

Inside Twig, whitespace doesn't matter. this means that we can add or remove spaces whenever we want:

{%for product    in      products%}
    <div class="span4">
{% endfor %}

Of course, this looks a bit uglier, so we usually keep just one space between everything. Outside of Twig (in the final HTML), all the whitespace is kept just like it appears. There are ways to make Twig control the whitespace of your file, which we'll talk about later.

Leave a comment!

Login or Register to join the conversation
Default user avatar
Default user avatar Nahuel Fernandez | posted 4 years ago

Hello, I'm trying to perform the challenges, but no matter how well my answer is, I get a connection rejection error in the test browser.
The error is the following "a93.main-challenges.knpuniv... rejected the connection."
What could it be??

1 Reply

Hey Nahuel!

Ah, sorry about that! Let me see if I can help :). First, if you try the challenge now, does the issue still happen? Does it happen any any coding challenge, or just this one?

Also, if you see the "rejected connection" again, could you try to copy that URL into your browser and see if it works? Make sure you have port :8000 at the end of the URL - so something like https://a93.main-challenges.knpuniversity.com:8000 (don't try that exact URL - it won't work - you get a new, unique URL for each new challenge - so use whatever the host name is in the error, if you see the error).

There are a few possible causes - the machine that's booted for you in the background may have been shut down, but you should get a clear error about this, so it's unlikely. Another possibility is that port 8000 (which is the port we use to talk to the server) is blocked by some firewall on your end).

Let me know what you find out! Cheers!

Default user avatar
Default user avatar hookedonweb_usa | posted 3 years ago

What code editor are you using?


Hey hookedonweb_usa

The all mighty PHPStorm https://www.jetbrains.com/e...



Hi, when I link the twig template to the controller I get the message 'template not found' I also don't get the autocompilation. How can I solve? I had already put templates as path folder in twig settings but the problems is still there. (I'm using symfony not drupal sorry maybe is the wrong place for ask this question)


hey Gballocc7

Do you have Symfony plugin installed and activated in your PhpStorm settings?



Yes! I've fixed that problem but now I get missing assets! Everything run fine but I haven't the suggestions from the idle


Check Symfony settings in PHPStorm(Languages & Frameworks -> PHP -> Symfony) on main tab check directory paths, and on Container and Routing tabs push Reset to defaults, default file paths should appear. After it save settings, and probably try to restart PHPStorm with cache and index invalidation.


1 Reply
Default user avatar
Default user avatar Danny Avery | posted 4 years ago

So, I have nothing coming up in my browser. Do you have an .sql file? I didn't see one in the code download. Thank you!


No .sql file needed, but I've just added a note to the top of this script about how to download the project and get it up and running locally :).


1 Reply
Default user avatar

Hi, I keep getting this error when running index.php locally. test.php works fine, but this error doesn't seem to go away and I can't get it to work.. please help! This is with the standard start files by the way. Followed all the instructions in de README, but it keeps popping up.

Fatal error: Uncaught Twig_Error_Loader: Unable to find template ".twig" (looked into: C:\xampp\htdocs\twig/templates). in C:\xampp\htdocs\twig\vendor\twig\twig\lib\Twig\Loader\Filesystem.php:197 Stack trace: #0 C:\xampp\htdocs\twig\vendor\twig\twig\lib\Twig\Loader\Filesystem.php(133): Twig_Loader_Filesystem->findTemplate('.twig') #1 C:\xampp\htdocs\twig\vendor\twig\twig\lib\Twig\Environment.php(265): Twig_Loader_Filesystem->getCacheKey('.twig') #2 C:\xampp\htdocs\twig\vendor\twig\twig\lib\Twig\Environment.php(312): Twig_Environment->getTemplateClass('.twig', NULL) #3 C:\xampp\htdocs\twig\vendor\twig\twig\lib\Twig\Environment.php(288): Twig_Environment->loadTemplate('.twig') #4 C:\xampp\htdocs\twig\index.php(54): Twig_Environment->render('.twig', Array) #5 {main} thrown in C:\xampp\htdocs\twig\vendor\twig\twig\lib\Twig\Loader\Filesystem.php on line 197


Hey jjaimy

You have to manually create the `homepage.twig` file, so the loader can find it :)


Default user avatar
Default user avatar jjaimy | MolloKhan | posted 4 years ago | edited

Hi MolloKhan!

Thanks for your reply! I have tried to that both in PHPStorm and by using the notepad program to create a homepage.twig file, yet it gives me the error anyway. For some reason it can't find the homepage.twig file, even thought it's there in the right directory (the templates folder).

Is there anything else I could try?

EDIT: Could it have something to do with the fact that C:\xampp\htdocs\twig/templates is being searched and the last 'slash' is a forward slash (/) instead of a backslash (\)?


Ohh, interesting! I believe this is an error related to Windows, try this change

// index.php
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');


$loader = new Twig_Loader_Filesystem(__DIR__ . DIRECTORY_SEPARATOR . 'templates');
Default user avatar

It still gives me the exact same error when going to localhost:8000/index.php, yet somehow it now DOES work when simply going to localhost:8000.

I have no idea why, but nonetheless I can continue the course this way, so as far as I'm concerned that's fixed! :)

Anyway, thank you so much for your help! <3


Oh, which web server are you using, apache? It's kind of weird that issue :)

Default user avatar

For this particual project I use the built in PHP sever that I summon through the terminal with php -S localhost:8000. Otherwise I indeed use Apache :)


Cool :)
I'm glad you can keep going on with the course, but if you find the fix for that sneaky weirdo bug, let us know!


Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial uses Twig 1. There are newer versions of Twig, but they don't contain significant differences. So, Twig on!

What PHP libraries does this tutorial use?

// composer.json
    "require": []