[英]Creating a file text with symfony2 and twig
我想用细枝从symfony2控制器生成文件文本。
像普通的html模板一样,但使用纯文本,然后将文件保存在某个位置。
可能吗 ?
终于明白了。
我想生成bash脚本。
在正确的位置创建模板,例如
myBundle/Resources/views/MyController/mytemplate.sh.twig
在ScriptGenerator类中
// Load the template $template = $this->twig->loadTemplate('myBundle:MyController:mytemplate.sh.twig'); // Render the whole template $script = $template->render($parameters);
如果要使用它,请放置此代码。
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); ... } }
是的,这可以做到。 您必须在路线定义(.txt)中输入正确的格式
您还必须设置正确的Content-Type
标头,
$response->headers->set('Content-Type', 'text/plain');
事实上, Response对象通常填充HTML代码,但它也可以包含纯文本(带有text-plain的Content-Type标头),图像或其他格式。
您还应该在模板名称上输入正确的格式,
XXXYourBundle:XXXX:temlate_name.txt.twig // In case you're using Twig as a templating Engine
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.