Brought to you with tenderness by the Knp team
KnpIpsum

A Symfony2 Tutorial Application

Twig tutorial

A sample twig template

Hello World, how are you today?

You can replace World by your name in the url.

Notice how you can use the name variable in the template. It comes from the controller, have a look at it!

In this template we have redefined the "content" block from the layout file (src/Knp/IpsumBundle/Resources/views/layout.html.twig)

Twig examples

Loops, if…

Comments

Tags

foo

Include

ok it works

Filters

What's the best: 1 or 2 or 3?

Code behind this page

User Story

src/Knp/IpsumBundle/Features/Twig.feature
Feature: Twig templates
  In order to maintain a sexy view layer
  As a Symfony2 developer
  I need to be able to use Twig

  Scenario: User clicks "Template" link on home page
    Given I am on homepage
    When I follow "Template"
    Then I should see "Hello World, how are you today"

  Scenario: User loads /twig/Edgar page
    When I go to "/twig/Edgar"
    Then I should see "Hello Edgar, how are you today"

Controller Code

src/Knp/IpsumBundle/Controller/TwigController.php:9
public function helloAction($name)
{
    return $this->render('KnpIpsumBundle:Twig:hello.html.twig', array(
        'name' => $name
    ));
}

Template Code

src/Knp/IpsumBundle/Resources/views/Twig/hello.html.twig
{% extends "KnpIpsumBundle::layout.html.twig" %}

{% block title "Twig tutorial" %}

{% block content %}
    <h1>A sample twig template</h1>
    
    <p>Hello <strong>{{ name }}</strong>, how are you today?</p>

    <p>You can replace {{ name }} by your name in the url.</p>
    
    <p>Notice how you can use the name variable in the template.
    It comes from the controller, have a look at it!</p>
    
     <p>In this template we have redefined the "content" block from the layout file
    (src/Knp/IpsumBundle/Resources/views/layout.html.twig)</p>

    <h1>Twig examples</h1>
    
    <h2>Loops, if…</h2>
    
    {% if true %}
        <ul>
        {% for name, type in {'edgar': 'cat', 'bob': 'dog'} %}
            <li><strong>{{ name }}</strong> is a {{ type }}</li>
        {% endfor %}
        </ul>
    {% endif %}
    
    <h2>Comments</h2>
    
    {# Well this is a comment #}
    
    <h2>Tags</h2>
    
    {% spaceless %}
        <div>
            <strong>foo</strong>
        </div>
    {% endspaceless %}
    {# output will be <div><strong>foo</strong></div> #}
    
    <h2>Include</h2>
    
    {% include 'KnpIpsumBundle:Twig:included.html.twig' with {'msg': 'ok it works'} %}
    
    <h2>Filters</h2>
    
    <p>What's the best: {{ [1, 2, 3]|join(' or ') }}?</p>
    
{% endblock %}