Symfony2 / Twig : Generate Alternate Absolute URL Path for use with CDN?

前端 未结 2 1776
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 12:20

This stackoverflow solution almost answers my question. But I want to generate CDN urls in Twig to more than just resources. I\'d like to generate them for dynamic

相关标签:
2条回答
  • 2021-02-03 12:52

    You can do it with the help of the question you linked by following way

    {{ asset(path('route',{'param1':'value'})) }}
    

    If you need to handle multiple CDN domains you can do it by following way

    In app/config.yml

    # app/config.yml
    #....
    templating:       
      engines: ['twig'] 
      packages:
        cdn1:
          base_urls: ["http://cdn1.domain.com"]
        cdn2:
          base_urls: ["http://cdn2.domain.com"]
    

    And then in your twig template file

    {{ asset('path/of/file', 'cdn1')
    

    OR

    {{ asset('path/of/file', 'cdn2')
    
    0 讨论(0)
  • 2021-02-03 12:54

    I don't know about the CDN stuff but as far as extending the url function, take a look at:

    Symfony\Bridge\Twig\Extension\RoutingExtension

    public function __construct(UrlGeneratorInterface $generator)
    {
        $this->generator = $generator;
    }
    public function getFunctions()
    {
        return array(
            'url'  => new \Twig_Function_Method($this, 'getUrl'),
            'path' => new \Twig_Function_Method($this, 'getPath'),
        );
    }
    public function getPath($name, $parameters = array())
    {
        return $this->generator->generate($name, $parameters, false);
    }
    
    public function getUrl($name, $parameters = array())
    {
        return $this->generator->generate($name, $parameters, true);
    }
    

    So you could get at getUrl there or you could insert you own UrlGenerator. Not sure which would be easier in your specific case. Probably making your own UrlGenerator.

    0 讨论(0)
提交回复
热议问题