简体   繁体   中英

Include assets in Twig Extension with Symfony2

I want to include asset with some script file in Twig extension. Eg 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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM