Twig Snippets

by | Oct 15, 2015 | Currently Editing, Developement, Important | 0 comments

Twig 1.8 Snippets

This is a collection of my most used Twig snippets, developed with Twig 1.8.

View Twig Docs

Simple Filters

1
2
3
4
5
6
7
// Urlify simple filter for Twig
$filter = new Twig_SimpleFilter('urlify', function ($string) {
     return URLify::filter($string);
});
$twig->addFilter($filter);
 
// Example: {{ variable-name|urlify }}
1
2
3
4
5
6
7
// hex2rgba simple filter for Twig
$filter = new Twig_SimpleFilter('hex2rgba', function ($string, $alpha = '1') {
     return Utils::hex2rgb($string, $alpha);
});
$twig->;addFilter($filter);
 
// Example: {{ product.colour|hex2rgba('0.25') }}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

1
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

IOC/Setup Class Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
<?php
/**
 * Created by PhpStorm.
 * User: stuart
 * Date: 02/10/15
 * Time: 11:41
 */
 
namespace App\Container;
 
use Twig_Autoloader;
use Twig_Loader_Filesystem;
use Twig_Environment;
use Twig_Extension_Debug;
use Twig_SimpleFilter;
use URLify\URLify;
use Utils;
 
 
/**
 * Class Twig
 * @package App\Container
 */
class Twig
{
 
    /**
     * @var string
     */
    public $rootPath;
 
    /**
     * @var string
     */
    public $cachePath;
 
    /**
     * @var string
     */
    public $templatePath;
 
    /**
     * @var Twig_Loader_Filesystem
     */
    public $twigLoader;
 
    /**
     * @var Twig_Environment
     */
    public $twig;
 
    /**
     * TwigConfig constructor.
     */
    public function __construct($rootPath)
    {
 
        $this->setRootPath($rootPath);
        $this->setCachePath($rootPath . DIRECTORY_SEPARATOR . 'cache');
        $this->setTemplatePath($rootPath . DIRECTORY_SEPARATOR . 'templates');
 
        Twig_Autoloader::register();
        $loader = new Twig_Loader_Filesystem($this->getTemplatePath());
        $this->setTwigLoader($loader);
 
        $twig = new Twig_Environment($loader, array(
            'cache' => $this->getCachePath(),
            'debug' => true,
        ));
        $twig->addExtension(new Twig_Extension_Debug());
 
        // an anonymous function
        $filter = new Twig_SimpleFilter('urlify', function ($string) {
            return URLify::filter($string);
        });
        $twig->addFilter($filter);
        $filter = new Twig_SimpleFilter('hex2rgba', function ($string, $alpha = '1') {
            return Utils::hex2rgb($string, $alpha);
        });
        $twig->addFilter($filter);
 
        $this->setTwig($twig);
        /**
         * Render Example:
         * $template = $twig->loadTemplate('teamgalleryitem.html');
         * echo $template->render(array('node' => $node));
         */
    }
 
    /**
     * @return string
     */
    public function getRootPath()
    {
        return $this->rootPath;
    }
 
    /**
     * @param string $rootPath
     */
    public function setRootPath($rootPath)
    {
        $this->rootPath = $rootPath;
    }
 
    /**
     * @return string
     */
    public function getCachePath()
    {
        return $this->cachePath;
    }
 
    /**
     * @param string $cachePath
     */
    public function setCachePath($cachePath)
    {
        $this->cachePath = $cachePath;
    }
 
    /**
     * @return string
     */
    public function getTemplatePath()
    {
        return $this->templatePath;
    }
 
    /**
     * @param string $templatePath
     */
    public function setTemplatePath($templatePath)
    {
        $this->templatePath = $templatePath;
    }
 
    /**
     * @return Twig_Loader_Filesystem
     */
    public function getTwigLoader()
    {
        return $this->twigLoader;
    }
 
    /**
     * @param Twig_Loader_Filesystem $twigLoader
     */
    public function setTwigLoader($twigLoader)
    {
        $this->twigLoader = $twigLoader;
    }
 
    /**
     * @return Twig_Environment
     */
    public function getTwig()
    {
        return $this->twig;
    }
 
    /**
     * @param Twig_Environment $twig
     */
    public function setTwig($twig)
    {
        $this->twig = $twig;
    }
 
    public function render($templateName, $data = array()) {
        $twig = $this->getTwig();
        $template = $twig->loadTemplate($templateName);
        return $template->render($data);
    }
 
    /**
     * @return string
     */
    public function testTemplate() {
        $twig = $this->getTwig();
        $template = $twig->loadTemplate('test.html');
        return $template->render(array());
    }
}

Advanced Loop Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
{% if product.datasheet.installation_items %}
 
        {% for paragraphItemKey, paragraphItem in product.datasheet.installation_items %}
 
        <div class="row">
 
            {% if paragraphItem|length == 1 %}
            <div class="col-xs-12">
                <p>
                    {{ paragraphItem[0][0]|raw }}
                </p>
            </div>
            {% endif %}
 
            {% if paragraphItem|length == 2 %}
            <div class="col-xs-3 row-title">
                <p>
                    {{ paragraphItem[0][0]|raw }}
                </p>
            </div>
 
            <div class="col-xs-9 paddingr0 pull-right">
                {% if paragraphItem[1]|length > 1 %}
                <ul>
                    {% endif %}
 
                    {% for paragraphFieldValueKey, paragraphFieldValue in paragraphItem[1] %}
                    {% if paragraphItem[1]|length > 1 %}
                    <li>
                        {% endif %}
 
                        {{ paragraphFieldValue|raw }}
 
                        {% if paragraphItem[1]|length > 1 %}
                    </li>
                    {% endif %}
 
                    {% endfor %}
 
                    {% if paragraphItem[1]|length > 1 %}
                </ul>
                {% endif %}
            </div>
            {% endif %}
 
            {% if paragraphItem|length == 3 %}
            <div class="col-xs-3 row-title">
                <p>
                    {{ paragraphItem[1][0]|raw }}
                </p>
            </div>
 
            <div class="col-xs-3 pull-right">
                {# The image field has the wrong index, see above. #}
                {% for paragraphFieldValueKey, paragraphFieldValue in paragraphItem[0] %}
 
                {% if ('.png' in paragraphFieldValue) or ('.jpg' in paragraphFieldValue) or ('.jpeg' in paragraphFieldValue) or ('.gif' in paragraphFieldValue) %}
                <img src="{{ paragraphFieldValue|raw }}" class="img-responsive" alt="" />
                {% endif %}
 
                {% endfor %}
            </div>
 
            <div class="col-xs-6 paddingr0 pull-right">
                {% if paragraphItem[2]|length > 1 %}
                <ul>
                    {% endif %}
 
                    {# The image field has the wrong index, so had to remap to 2 #}
                    {% for paragraphFieldValueKey, paragraphFieldValue in paragraphItem[2] %}
                    {% if paragraphItem[2]|length > 1 %}
                    <li>
                        {% endif %}
 
                        {{ paragraphFieldValue|raw }}
 
                        {% if paragraphItem[2]|length > 1 %}
                    </li>
                    {% endif %}
 
                    {% endfor %}
 
                    {% if paragraphItem[2]|length > 1 %}
                </ul>
                {% endif %}
 
            </div>
            {% endif %}
 
        </div>
 
        <hr />
 
        {% endfor %}
 
        {% endif %}
        <!-- END: INSTALLATION PAGE -->
Share This