Include assets in Twig Extension with Symfony2

2019-08-09 09:02发布

问题:

I want to include asset with some script file in Twig extension. E.g. I want to declare twig function {{ init_project() }}, but when I writing in my twig function '<script type="text/javascript" src="{{ asset('bundles/mybundle/js/script.js') }}"></script>', it dont work, it return 404 error in debug panel of browser. So how I can do this?

回答1:

Look at the 'asset' twig function :

You can find it in \Symfony\Bundle\TwigBundle\Extensions\AssetsExtension

public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null)
    {
        $url = $this->container->get('templating.helper.assets')->getUrl($path, $packageName, $version);

        if (!$absolute) {
            return $url;
        }

        return $this->ensureUrlIsAbsolute($url);
    }

Instead of calling '{{asset}}' in your extension, just call the public function getAssetUrl()