2013-04-25 45 views

回答

4

終於得償所願。

我想生成bash腳本。

  1. 建立在正確的地方模板如

    myBundle/Resources/views/MyController/mytemplate.sh.twig 
    
  2. 在ScriptGenerator類

    // Load the template 
    $template = $this->twig->loadTemplate('myBundle:MyController:mytemplate.sh.twig'); 
    // Render the whole template 
    $script = $template->render($parameters); 
    
  3. 如果你想使用它,把這個代碼。

    namespace myproject\myBundle\Controller; 
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
    
    use myproject\myBundle\Generator\ScriptGenerator; 
    
    class myController extends Controller 
    { 
        public function myAction() 
        { 
         $twig = $this->get('twig'); 
         $generator = new ScriptGenerator($twig); 
         $parameters = array(
          'a parameter' => "whatever" 
         ); 
         $script = $generator->setScript($parameters); 
    
         file_put_contents('whereyouwant',$script); 
    
         ... 
        } 
    } 
    
+0

對於純文本,Twig文件可能希望利用Raw過濾器來抑制HTML轉義。 http://twig.sensiolabs.org/doc/filters/raw.html – IanMcL 2015-09-15 10:21:39

2

是的,這可以做到。你已經把正確格式的路線定義範圍內的文件(.txt)

你也已經確立正確的Content-Type頭,

$response->headers->set('Content-Type', 'text/plain'); 

其實Response object通常與HTML代碼填充,但它也可以包含純文本(帶有文本/純文本的Content-Type標頭),圖像或其他格式。

你也應該把你的模板的名稱格式正確,

XXXYourBundle:XXXX:temlate_name.txt.twig // In case you're using Twig as a templating Engine 
+1

這很好!但我想生成該文件並將其保存在用戶文件夾中。怎麼做 ?我正在嘗試這種方法來生成郵件(http://alexandre-salome.fr/blog/Generate-Mails-With-Twig)和$ template-> render函數,但我需要填充多個塊之前呈現... – user1254498 2013-04-25 15:45:53