IngmarBoddington
2/28/2013 - 11:30 AM

Twig Templating basics (in Symfony) | Key: <required_value>, [optional]

Twig Templating basics (in Symfony) | Key: <required_value>, [optional]

Template naming convention
    <bundle>:<controller>:<template>
        <bundle> translates to /src/BundleStart/BundleEnd/ (e.g. AcmeBlogBundle -> src/Acme/BlogBundle)
        <controller> means template in /Resources/Views/<controller>
        <template> is actual name of file in format <name>.<format>.<engine> e.g. index.html.php or smeg.xml.twig
    ::base.html.twig means template in application wide dir i.e. app/Resources/Views/


{{ <variable> }} - Output value

    Variables
        user.name //ie can use dot notation for members
        cycle([<values>], <variable>) //cycle between values when variable changes (useful in for loop
        <variable>|<filter> //Run the variable through a filter
        parent() //Include from parent, use in child blocks
        dump(<variable>) //Debug output, must be enabled (see below)
        Automatically escaped

    Filters
        upper //Uppercase
        lower //Lowercase
        raw //Do not escape output

{% <control statement> %} - A control statement

    Control statements: 
        if <condition>
        else
        elseif
        for <var> in <array>
        endfor
        for <var> in <array> if <condition>


Identify a section which can be overridden by child templates:
    {% block <name> %} 
        <Markup>
    {% endblock %}

Child templates (replace named blocks in parent)
    {% extends <template_identifier> %} //Place at start of file, identifies parent
    {% block <name> %} 
        <Markup>
    {% endblock %}
    ....

Including a template (and optionally pass variables)
    {% include <template>
        [with {'<varname>': <value|varnameInParent>, ...}]
    %}

To use a controller render directly in a template (is this symfony only?)
    {% render url('<name_of_route>', { 'max': 3 }) %}
    //Route must map to controller in app/config/config.yml in Symfony

Globals (format for app/config/config.yml in Symfony):
    twig:
        globals:
            <var_name>: <value>

Debug enable (format for app/config/config.yml in Symfony):
    services:
        acme_hello.twig.extension.debug:
            class:        Twig_Extension_Debug
            tags:
                 - { name: 'twig.extension' }