axel_leb axel_leb - 3 months ago 64
PHP Question

Asset Function without Symfony in Twig

I'd like to use the asset function into my project where I'm only using Twig.
I tryed to use it but php return me this :


Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unknown "asset" function in "./Default/base.html.twig"

Answer

The solution is on sensiolabs.org.

I added this in conf.php :

//config/config.php
require_once('../vendor/autoload.php');

//twig
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('../app/views');
$twig = new Twig_Environment($loader);
$twig->addFunction(new \Twig_SimpleFunction('asset', function ($asset) {
    // implement whatever logic you need to determine the asset path

    return sprintf('../assets/%s', ltrim($asset, '/'));
}));

See you !

Comments