1

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?

2
  • 2
    Have you checked the twig (not the symfony) manual? It shows how to add extensions. twig.sensiolabs.org/doc/api.html#using-extensions Commented Feb 15, 2014 at 13:06
  • yes but I don't know how to access the builtin extensions of symfony2 Commented Feb 15, 2014 at 13:10

2 Answers 2

5

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());
// ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.Also with the risk of sounding dimwitted: is it possible to configure twig so that you don't have to load the extension everytime like the built-in extensions?
1

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

hey man,how is twig_loader_string being used here?i read the documentation but couldn't figure.
It is used so $twig->render() takes a string instead of a file as first argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.