【问题标题】:Creating a file text with symfony2 and twig使用 symfony2 和 twig 创建文件文本
【发布时间】:2013-04-25 15:15:42
【问题描述】:

我想用 twig 从 symfony2 控制器生成文件文本。

与普通的 html 模板一样,但使用纯文本,并将文件保存在某处。

有可能吗?

【问题讨论】:

    标签: php file symfony text twig


    【解决方案1】:

    终于明白了。

    我想生成 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);
      
              ...
          }
      }
      

    【讨论】:

    【解决方案2】:

    是的,这是可以做到的。您必须在路由定义 (.txt) 中输入正确的格式

    您还必须设置正确的Content-Type 标头,

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

    事实上,Response object 通常由 HTML 代码填充,但它也可以包含纯文本(带有 text/plain 的 Content-Type 标头)、图像或其他格式。

    您还应该在模板名称上使用正确的格式,

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

    【讨论】:

    • 这很好!但我想生成文件并将其保存在用户文件夹中。怎么做 ?我正在尝试这种方法来生成邮件(alexandre-salome.fr/blog/Generate-Mails-With-Twig)和函数 $template->render 但我需要在渲染之前填充多个块...
    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多