2014-10-07 40 views
5

我需要生成一個郵件模板成Symfony2的命令檢索app.request,一切正常,除了{{app.request}}爲空進入枝杈(我需要它sheme和httpHost)因爲它是從cli環境中調用的。我試圖改變這個範圍:Symfony2的:在枝杈從命令

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

但它沒有提供app.request。有解決方案來解決這個問題嗎?

+1

有**是不是**的請求,因爲你在命令行調用它。從HTTP請求構建請求 - 命令不會生成HTTP請求。你想從請求中獲得什麼? – 2014-10-07 13:29:10

+0

我正在檢測這樣的響應......我需要它來生成一些圖像src:這些模板也用於我的控制器,我想避免創建變量來生成該src。 – Spope 2014-10-07 13:33:34

+0

所以,是的,沒有要求,因此沒有計劃或主機。渲染模板時可以傳入參數。或者根據命令中的標誌創建自定義的Twig函數來生成'src'。 – 2014-10-07 13:42:20

回答

6

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 
} 
} 

There is a specific paragraph for this problem on the guide

3

在您的命令:

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

在模板:

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

就個人而言,我會抽象的IMG SRC一代的功能,而不是硬編碼這個邏輯遍佈在模板的地方。