[英]Symfony2: Get HTML from another file in controller
In my Symfony2 project, I would like to get the HTML of a file and put it in a variable in my controller. 在我的Symfony2项目中,我想获取文件的HTML并将其放在我的控制器中的变量中。
I have a controller function like this: 我有这样的控制器功能:
public function myControllerAction()
{
$htmlOtherFile = '';
return $this->render('@MyBundle/myTargetFile.html.twig', ['htmlOtherFile' => $htmlOtherFile]);
}
The html file I would like to import is in my views folder: htmlOtherFile.html.twig
我要导入的html文件位于我的views文件夹中:
htmlOtherFile.html.twig
How can I get the HTML
of this file into my $htmlOtherFile
variable? 如何将此文件的
HTML
放入我的$htmlOtherFile
变量中? I have already tried with file_get_contents
, but without success. 我已经尝试过使用
file_get_contents
,但没有成功。
all you need to do is call renderView
from your controller on the template and put the contents in a variable. 您需要做的就是从模板上的控制器调用
renderView
并将内容放在变量中。
$html = $this->renderView('/path/myTargetFile.html.twig', [/*options in here*/]);
Be sure to call renderView
and not render
on its own as that will return a Response
instance, and not any HTML. 一定要调用
renderView
而不是自己render
,因为它会返回一个Response
实例,而不是任何HTML。
Alternatively, you can call: 或者,您可以致电:
$this->render('/path/myTargetFile.html.twig', [/*options in here*/])->getContent();
to return the html from the response. 从响应中返回html。
如果是twig文件 - 你可以试试这个:
$this->renderView('/path/to/template.html.twig', []);
You can call a controller directly from you twig file if you want. 如果需要,您可以直接从您的twig文件中调用控制器。
Use the syntax {{ render(controller('MyBundle:functionName')) }}
使用语法
{{ render(controller('MyBundle:functionName')) }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.