2
votes

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"

2

2 Answers

17
votes

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, '/'));
}));
1
votes

That's because Assetic itself is a standalone PHP library.
So to use asset in twig you need to install the bundle.

Run the following composer command to install assetic bundle.

composer require symfony/assetic-bundle

Without installing the standalone package, twig won't able to find the asset function.