I want to use some of the builtin symfony2 extensions(e.g:humanize,yaml_dump) for twig for a website not developed in symfony but using a twig engine.how can I do that?
-
2Have you checked the twig (not the symfony) manual? It shows how to add extensions. twig.sensiolabs.org/doc/api.html#using-extensionsCerad– Cerad2014-02-15 13:06:19 +00:00Commented Feb 15, 2014 at 13:06
-
yes but I don't know how to access the builtin extensions of symfony2user2268997– user22689972014-02-15 13:10:03 +00:00Commented Feb 15, 2014 at 13:10
2 Answers
The symfony/twig-bridge package provides the symfony-specific twig extensions.
These include i.e. the YamlExtension that provides the yaml_dump filter and the FormExtension that provides the humanize filter.
The extensions can be found in the Extension folder.
I strongly advise you to install the package via composer to get the package's dependencies automatically.
composer require symfony/twig-bridge:~2.3
Further composer will automatically register the classes in the autoloader (vendor/autoload.php) for you.
Now you just need to add the extensions to twig as described in the documentation.
$twig->addExtension(new \Symfony\Bridge\Twig\Extension\YamlExtension());
// ...
1 Comment
A complete example, with an extension class and a quick extension (a new filter) :
<?php
require_once("vendor/autoload.php");
$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
// here we add the extension class (taken from @nifr answer)
$twig->addExtension(new \Symfony\Bridge\Twig\Extension\YamlExtension());
// here we add a new filter quickly
$filter = new Twig_SimpleFilter('paragraph', function ($argument) {
return "<p>{$argument}</p>";
}, array('pre_escape' => 'html', 'is_safe' => array('html')));
$twig->addFilter($filter);
// demo
echo $twig->render('{{ "hello" | paragraph }}');
2 Comments
$twig->render() takes a string instead of a file as first argument.