Symfony2: fetching app.request in Twig from command

I need to create a mail template in the Symfony2 command, everything works, except that {{app.request}} is null in Twig (I need this for sheme and httpHost), because it is called from the cli context. I tried changing this area with:

$this->getContainer()->enterScope('request'); $this->getContainer()->set('request', new Request(), 'request'); 

but it does not provide app.request. Is there any solution to fix this?

+5
source share
2 answers

The Symfony Guide offers to configure the request context globally, so you perform a static configuration without parameters and programmatically set the context of the Symfony Router component.

 # app/config/parameters.yml parameters: router.request_context.host: example.org router.request_context.scheme: https router.request_context.base_url: my/path // src/Acme/DemoBundle/Command/DemoCommand.php // ... class DemoCommand extends ContainerAwareCommand { protected function execute(InputInterface $input, OutputInterface $output) { $context = $this->getContainer()->get('router')->getContext(); $context->setHost('example.com'); $context->setScheme('https'); $context->setBaseUrl('my/path'); // ... your code here } } 

There is a specific paragraph to this problem in the manual.

+6
source

At your command:

 $this->render('template.html.twig', [ 'scheme' => 'https', 'host' => 'example.com', ]); 

In your template:

 {% if app.request is defined %}{{ app.request.scheme }}{% else %}{{ scheme|default('http') }}{% endif %} 

Personally, I would divert the generation of img src to a function, instead of hard-coding this logic everywhere in templates.

+3
source

Source: https://habr.com/ru/post/1204178/


All Articles