I need to generate a mail template into a Symfony2 command, everything works except that {{app.request}} is null into Twig (I need it for sheme and httpHost) because it is called from a cli context. I've tried to change that scope with :
$this->getContainer()->enterScope('request');
$this->getContainer()->set('request', new Request(), 'request');
but it's not providing app.request . Is there a solution to fix this ?
The Symfony Guide suggest to configure the Request Context Globally, so you make a static configuration un your parameters and set the Context of the Symfony Router Component programmatically.
# 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 for this problem on the guide
In 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 abstract the img src generation to a function, instead of hardcoding that logic all over the place in templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With