Archives du mot-clef twig

Twig filter example

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../src/Views',
    'twig.options'          => array(
        'charset'           => 'utf-8',
        'strict_variables'  => true,
        'cache'             => __DIR__.'/cache'
    )
));
 
$app->before(function() use($app) {
    $app['twig']->addExtension(new \Twig\MyExtension($app));
});
<?php
namespace Twig;
 
class MyExtension extends \Twig_Extension {
 
    public function getName() {
        return 'my';
    }
 
    public function getFilters() {
        return array(
            'link' => new \Twig_Filter_Method($this, 'link_filter', array('is_safe' => array('html'))),
        );
    }
 
    public function link_filter($ressource, $type = null) {
        $img_regex = '#(gif|jpe?g|png)$#i';
        $url_regex = '#^(https?:\/\/)#i';
        if(!$type) {
            if(preg_match($img_regex, $ressource)) {
                $type = 'img';
            } else if(preg_match($url_regex, $ressource)) {
                $type = 'a';
            }
        }
        switch($type) {
        case 'img':
            return '<img src="'.$ressource.'"/>';
            break;
        case 'a':
            return '<a href="'.$ressource.'">'.$ressource.'</a>';
            break;
        default:
            return $ressource;
        }
    }
}
<p>
{{ ressource|link }}
</p>

symfony2 twig i18n date

sudo aptitude install php5-intl

app/config/config.yml

services:
    twig.extension.intl:
       class: Twig_Extensions_Extension_Intl
       tags:
           - { name: twig.extension }

In twig template

{{ game.created_at| localizeddate('full', 'none') }}

twig macro link title translation

{% macro link(route, title, name, attr) %}
{% spaceless %}
<a href="{{ path(route) }}" title="{{ title|trans({}, 'link') }}"{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>{{ name|trans({}, 'link') }}</a>
{% endspaceless %}
{% endmacro %}
 
<!-- Usage 
{{ macro.link('route_name', 'link title', 'link name', {'class':'css_class'}) }}
-->
 
<!-- HTML
<a href="/dashboard" title="Manage" class="pouet">Manage</a>
-->