Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : Retrieve app.request in Twig from a command

Tags:

php

twig

symfony

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 ?

like image 899
Spope Avatar asked Oct 07 '14 13:10

Spope


2 Answers

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

like image 133
Matteo Avatar answered Nov 02 '22 04:11

Matteo


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.

like image 41
Dan Blows Avatar answered Nov 02 '22 05:11

Dan Blows