Twig Templates

A brief introduction to Twig; a fast, concise, and secure template engine for PHP.

Twig Templates

Overview

  1. Create a New Project
  2. Install Twig
  3. Create a Twig Layout
  4. Initial Twig Template
  5. Using Variables
  6. Conditionals and Loops
  7. Including Templates
  8. Additional Information

Create a New Project

Local Webserver

Linux + Apache + MySQL + PHP

Learn More

Create a New Project

New Project Structure

*/NewProject

*/NewProject/src

*/NewProject/views

*/NewProject/index.php

 

 

 

*/path/to/web/directory

Install Twig

Composer

Dependency Manager for PHP

Learn More

Install Twig

Install Twig

*/NewProject/composer.json

{
    "autoload": {
        "psr-4": {
            "NewProject\\Classes\\": "src/"
        }
    },
    "require": {
        "twig/twig": "~1.0"
    }
}

> php composer.phar install

Install Twig

Install Twig (Alternative)

> php composer.phar init

Search for a package: Twig

Enter package # to add ...: 0

{
    "autoload": {
        "psr-4": {
            "NewProject\\Classes\\": "src/"
        }
    },
    "require": {
        "twig/twig": "~1.0"
    }
}

Install Twig

*/NewProject/index.php

<?php

require_once 'vendor/autoload.php';
require_once('vendor/twig/twig/lib/Twig/Autoloader.php');

Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('views');

$twig = new Twig_Environment($loader, array(
    'cache' => 'cache',
));

Add to index.php

Create a Twig Layout

*/NewProject/views/layout.html

<!DOCTYPE html>
<html>
    <head>
        <style>
            h1 {
                color: blue;
            }
        </style>
    </head>

    <body>
        {% block content %}

        {% endblock %}
    </body>
</html>

Create layout.html

Initial Twig Template

*/NewProject/views/index.html

{% extends 'layout.html' %}

{% block content %}
 
    <h1>Hello World!</h1>

{% endblock %}

Create index.html

Initial Twig Template

*/NewProject/Classes/Page.php

<?php

namespace NewProject\Classes;

class Page
{
    public function index()
    {
        return [ 
            'salute' => 'goodnight',
            'target' => 'moon'
         ];
    }
}

Create Page.php

Initial Twig Template

*/NewProject/index.php

<?php

...

use NewProject\Classes\Page;

...

$page = new Page();

echo $twig->render('index.html', $page->index());

Use Page.php and index.html

Initial Twig Template

localhost/NewProject/index.php

View Initial Twig Template

Hello World!

Let's Review!

What is the purpose of views/layout.html?

What is the purpose of Page.php's index() function?

What is the purpose of the {% block content %}{% endblock %} tags?

Let's Review!

What is the purpose of views/layout.html?

Provide HTML, CSS, and Javascript that is the same for multiple templates

Let's Review!

What is the purpose of Page.php's index() function?

To prepare data for the index.html template.

Let's Review!

What is the purpose of the {% block content %}{% endblock %} tags?

To identify where in layout.html to place the template content.

Using Variables

*/NewProject/views/index.html

{% extends 'layout.html' %}

{% block content %}
 
    <h1>{{ salute }} {{ target }}!</h1>

{% endblock %}

Use variables from Page.php index()

*/NewProject/Classes/Page.php

        return [ 
            'salute' => 'goodnight',
            'target' => 'moon'
         ];

Using Variables

View Your Page

localhost/NewProject/index.php

goodnight moon!

Using Variables

Modify Your Variables

*/NewProject/views/index.html

{% extends 'layout.html' %}

{% block content %}
 
    <h1>{{ salute|title }} {{ target|title }}!</h1>

{% endblock %}

Goodnight Moon!

Using Variables

String Filters

  • {{ salute|capitalize }} = Goodbye
  • {{ salute|lower }} = goodbye
  • {{ salute|upper }} = GOODBYE

Number Filters

  • {{ -1234.567|round }} = -1235
  • {{ -1234.567|abs }} = 1234.567
  • {{ -1234.567|number_format(2) }} = -1,234.56

Set Variable Value

  • {% set greeting = salute ~ target %}

{{ greeting|title }} = Goodbye Moon

Learn More

Let's Review!

How do we print the value of a variable in Twig?

How do we apply a Twig filter to a variable?

How are action tags marked differently from display tags?

Let's Review!

How do we print the value of a variable in Twig?

Surround the variable name with double curly brackets:

{{ foo }}

Let's Review!

How do we apply a Twig filter to a value?

Follow the value with a pipe and the name of the filter:

{{ foo|title }}

Let's Review!

What signifies an action tag as opposed to a display tag?

Surround the action with curly-bracket percent-sign pairs:

{% set foo = bar %}

Conditionals and Loops

Conditionals

*/NewProject/views/index.html

{% if target|lower == 'sun' %}
    {% set title_color = 'red' %}
{% else %}
    {% set title_color = 'purple' %}
{% endif %}

<h1 style="color:{{ title_color }}">
    {{ salute|title }} {{ target }}!
</h1>

Conditionals and Loops

Loops

*/NewProject/Classes/Page.php

public function index()
{        
    return [ 
        'salute' => 'Goodnight',
        'my_set' => [ 
            'red' => 'Sun', 
            'blue' => 'Moon',
            'purple' => 'Stars' 
        ]
     ];
}

Conditionals and Loops

Loops

*/NewProject/views/index.html

{% for key,value in my_set %}

    <h1 style="color: {{ key }}">
        {{ loop.index }}. {{ salute }} {{ value }}!
    </h1>

{% endfor %}

1. Goodnight Sun!

2. Goodnight Moon!

3. Goodnight Stars!

Conditionals and Loops

Loops with Objects or Nested Assoc Arrays

*/NewProject/views/index.php


    {% for record in my_records %}
        <a href="{{ record.link }}">
            <h1 style="color: {{ record.color }}">
                {{ record.title }}
            </h1>
        </a>
        <p>{{ record.description }}</p>
    {% endfor %}

Let's Review!

How do we access the keys when looping through an array?

How do we access an object's properties?

How do we access an array value by key?

How can we get the current iteration count in a loop?

Let's Review!

How do we access the keys when looping through an array?

By providing a key name followed by a comma and a value name in the loop declaration:

{% for key,value in array %} 

Let's Review!

How do we access an object's properties?

By using a dot, followed by the property name:

myObject.objectProperty

*Bracket notation also works:

myObject['objectProperty']

Let's Review!

How do we access an array value by key?

Just like an object:

myArray.arrayKey

*Bracket notation also works:

myArray['arrayKey']

Let's Review!

How can we get the current iteration count in a loop?

loop.index

Including Templates

Create decor.html

*/NewProject/views/decor.html

<hr style="color: red">
<hr style="color: blue">
<hr style="color: purple">

*/NewProject/views/index.html

{% extends 'layout.html' %}

{% block content %}

    {% include 'decor.html' %}
        
    <h1>{{ salute|title }} {{ my_set.blue }}!</h1>

    {% include 'decor.html' %}

{% endblock %}

Including Templates

View your assembled Templates

localhost/NewProject/index.php

Goodnight Moon!

Twig Templates

Additional Information

http://twig.sensiolabs.org/

Questions?

Margaret Staples

@dead_lugosi on twitter

deadlugosi on freenode

TwigLesson

By Margaret Staples

TwigLesson

  • 674
Loading comments...

More from Margaret Staples