我需要在Symfony2命令中生成一个邮件模板,一切正常,除了{{app.request}}在Twig中为空(我需要它用于sheme和httpHost),因为它是从cli上下文调用的.我试图改变这个范围:
$this->getContainer()->enterScope('request');
$this->getContainer()->set('request', new Request(), 'request');
Run Code Online (Sandbox Code Playgroud)
但它没有提供app.request.有解决方案来解决这个问题吗?
Symfony指南建议在全局配置请求上下文,因此您可以使用参数进行静态配置,并以编程方式设置Symfony路由器组件的上下文.
# 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
}
}
Run Code Online (Sandbox Code Playgroud)
在你的命令下:
$this->render('template.html.twig', [
'scheme' => 'https',
'host' => 'example.com',
]);
Run Code Online (Sandbox Code Playgroud)
在您的模板中:
{% if app.request is defined %}{{ app.request.scheme }}{% else %}{{ scheme|default('http') }}{% endif %}
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我会将 img src 生成抽象为一个函数,而不是在模板中到处硬编码该逻辑。
| 归档时间: |
|
| 查看次数: |
2542 次 |
| 最近记录: |