Symfony2阻止标准php包含?

时间:2012-09-14 12:42:09

标签: php symfony include

我有一种情况,我打算离开面向对象的大纲,只是将一个原始的php文件包含到我的一个控制器中。

我想在实体的表单twig文件中包含未知数量的额外表单字段(这些表单字段在我想要包含的单独文件中定义)。

我的意图是 - 在提交操作中 - 循环遍历这些字段(比如data_1,data_2等)并序列化它们并将它们存储在实体属性“data”中。然后,根据模板类型输出该实体的结果的视图将知道预期的多少和多少额外字段并以正确的方式输出它们,这要归功于类似的设计,包括每个视图模板模板类型。

现在,这样做:

    //All template form files store all their html in $output
    include '/'.$templatePath.'/form.php';

    return $output;

我收到symfony错误(不是php错误!)说

Warning: include(/main/1/form.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in /var/www/biztv/src/BizTV/ContentManagementBundle/Controller/DefaultController.php line 136

所以,这只是说我错误地追踪了我想要包含的内容,或者就像我怀疑的那样,是否禁止使用symfony2?任何其他方法来完成我在这里尝试的东西?

1 个答案:

答案 0 :(得分:3)

只看你的代码,你的路径的开头有一个斜杠,它将指向根文件系统......

使用正确的相对路径(假设您当前的文件是Controller / xxx.php,而您的表单位于Forms / form.php中):

include __DIR__.'/../Forms/form.php';

但是你应该使用输出缓冲来捕获包含.php文件的结果,然后将内容传递给你的twig模板。否则可能会干扰应该发送的标题等。

在你的控制器中:

ob_start();
include __DIR__.'/../Forms/form.php';
$formContent = ob_clean();

...

return $this->render('tpl.html.twig', array(
    'form_content' => $formContent,
));

然后在你的树枝模板中:

{{ form_content|raw }}