php - 使用 symfony2 和 twig 创建文件文本

标签 php file symfony text twig

我想用 twig 从 symfony2 Controller 生成一个文件文本。

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

这可能吗?

最佳答案

终于明白了。

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

关于php - 使用 symfony2 和 twig 创建文件文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16218564/

相关文章:

ajax - 如何根据用户选择获取实体的子项(即两个实体 A 和 B B 的列表基于所选的 A )

symfony - [PDO异常] : SQLSTATE[28000] [1045] Access denied for user 'root' @'localhost' (using password: NO) Symfony2

php - paypal 自定义金额变量 BMUpdate?

php - 解析错误 : syntax error, unexpected T_ELSE, expecting T_FUNCTION in/home/petit/public_html/system/database/mysqli.php on line 54

c++ - 头文件和cpp文件

regex - 如何在复制 vfat 期间重命名文件

php - 如何修复 YAML 文件上的 "Circular reference"错误?

php - MySQL before Trigger,使用查询设置多个字段

php - 第一次点击,原始页面即将到来。但是,在第二次点击时,出现 'Page Not Found' 错误。 - Yii2-App-Basic

Python:计算一个单词在文件中出现的次数