How to use absolute path in twig functions

后端 未结 9 984
情话喂你
情话喂你 2020-12-04 16:35

I have an application with Symfony2 (2.2). When I want to send a mail, I\'m having trouble with the paths, which are all relative paths and obviously aren\'t working inside

相关标签:
9条回答
  • 2020-12-04 16:58

    The following works for me:

    <img src="{{ asset('bundle/myname/img/image.gif', null, true) }}" />
    
    0 讨论(0)
  • 2020-12-04 17:01

    You probably want to use the assets_base_urls configuration.

    framework:
        templating:
            assets_base_urls:
                http:   [http://www.website.com]
                ssl:   [https://www.website.com]
    

    http://symfony.com/doc/current/reference/configuration/framework.html#assets


    Note that the configuration is different since Symfony 2.7:

    framework:
        # ...
        assets:
            base_urls:
                - 'http://cdn.example.com/'
    
    0 讨论(0)
  • 2020-12-04 17:02

    Additional info to generate absolute URL using a command (to send an email for instance)

    In a command, {{ absolute_url(path('index')) }} is not working out of the box.

    You will need to add the additional configuration shown in antongorodezkiy's answer.

    But in case you don't want to change the configuration because you are not sure how it could impact the whole app, you can configure the router in the command.

    Here is the doc :

    https://symfony.com/doc/3.4/console/request_context.html

    Here is the code :

    use Symfony\Component\Routing\RouterInterface;
    // ...
    
    class DemoCommand extends Command
    {
        private $router;
    
        public function __construct(RouterInterface $router)
        {
            parent::__construct();
    
            $this->router = $router;
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $context = $this->router->getContext();
            $context->setHost('example.com');
            $context->setScheme('https');
            $context->setBaseUrl('my/path');
    
            $url = $this->router->generate('route-name', ['param-name' => 'param-value']);
            // ...
        }
    }
    

    To generate the URL in the Twig template

    <a href="{{ absolute_url(path(...)) }}"></a>
    

    You can fetch the HOST and SCHEME from your env file

    $context = $this->router->getContext();
    $context->setHost($_ENV['NL_HOST']);
    $context->setScheme($_ENV['NL_SCHEME']);
    

    Just define the variable in .env and .env.local files

    NL_HOST=mydomain.com
    NL_SCHEME=https
    
    0 讨论(0)
提交回复
热议问题