symfony2用twig生成静态html

Lt.*_*Lt. 5 symfony twig

有没有办法将hig代码从twig模板放入html文件.我的意思是,在这种情况下

$html = $this->render('SiteBundle:Generated:home_news.html.twig', array('news' => $news))->getContent();
Run Code Online (Sandbox Code Playgroud)

有没有办法可以做到这一点?

$html->output($html_file);
Run Code Online (Sandbox Code Playgroud)

它使用模板生成一个html文件.

我这样做是因为我从wordpress博客获得了新闻,我想在主页上显示最新消息.所以我想把我网站的新闻放在一个静态文件中,以避免在每个家庭请求中生成它.

Vit*_*ian 6

如果你仔细检查文档,你会发现这一章,其中说:

$content = $this->renderView('AcmeHelloBundle:Hello:index.html.twig', array('name' => $name));
Run Code Online (Sandbox Code Playgroud)

  • 那么`file_put_contents()`你的`$ content` - 不是吗?:) (3认同)
  • 谢谢你的回复,但对不起,我猜你还不懂我.我不想显示树枝模板的输出.我想将这些内容保存到html文件中,我将在其他地方使用. (2认同)
  • 是的,但我想问一个用树枝或S2做的方法 (2认同)
  • 无法直接呈现文件.将渲染输出作为字符串并使用`file_put_contents()`就可以了. (2认同)

cha*_*asr 5

要完成@VitalityZurian 的回答:

首先,生成您的标记:

$content = $this->renderView('AcmeHelloBundle:Hello:index.html.twig', array('name' => $name));
Run Code Online (Sandbox Code Playgroud)

然后,写入文件:

$file = file_put_contents($filename, $content);
Run Code Online (Sandbox Code Playgroud)

您可以使用 Symfony2 帮助方法来处理包中的位置:

$bundleResourcesDir = $this->get('kernel')->locateResource('@AcmeAnotherBundle/Resources/views');
file_put_contents($bundleResourcesDir.'/index.html.twig`
Run Code Online (Sandbox Code Playgroud)

并检索它:

$view = $this->get('kernel')->locateResource('@AcmeAnotherBundle/Resources/views/index.html.twig');
Run Code Online (Sandbox Code Playgroud)