Search code examples
phpsymfonyframeworkstwigsilex

Cannot override frozen service "twig.app_variable" - Dynamic path to asset function


I understand the error I get but can't figure why...

So here is my problem and why I got this error :

1/ I have a php variable $wdep that give my the path where I need to find my /web file (css, js, lib and img) :

if($_SERVER['SERVER_NAME'] == "127.0.0.1"){
    $wdep = "../../_wdep/v2/mywebsite/";
} else {
    $wdep = "https://wdep ... /v2/mywebsite/"; // I cut some info but the link is valid
}

2/ Now, when I registered my Twig Provider according to the Twig documentation, I can't use my css, js, etc. :

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../views',
));
$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
));

This works, but in my template but when use the asset() function it doesn't work : it's normal because I need to add my $wdep path to get it, so this

<link type="text/css" rel="stylesheet" href="{{ asset('/lib/bootstrap/css/bootstrap.css') }}" />
<script type="text/javascript" src="{{ asset('/lib/jquery/jquery-3.3.1.min.js') }}"></script>
<img src="{{ asset('/img/logo/logo.png') }}" alt="Logo">

don't work.

3/ According to the documentation about the asset() function (here), I tried to do those

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.base_urls' => $wdep
));

OR

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.named_packages' => array(
        'css' => array('base_urls' => array($wdep)),
        'img' => array('base_urls' => array($wdep)),
        'js'  => array('base_urls' => array($wdep)),
        'lib' => array('base_urls' => array($wdep)),
    ),
));

And get my Cannot override frozen service "twig.app_variable" error...

Maybe I am missing something, but do you you know why and how I can add my $wdep to my asset() function to make it works please?


Solution

  • I solve my problem just with this line I added after I registered TwigServiceProvider() and AssetServiceProvider():

    $app['assets.base_path'] = $wdep;
    

    I used some var_dump($app) to find it but I'd like to understand why I can't do it when I registered my AssetServiceProvider() ?