douzhe9075
2015-08-21 11:30
浏览 31
已采纳

哪个在Symfony2中更好:渲染控制器或包含模板?

I develop university site with Symfony2. Besides I'm almost newbie in Symfony.

Index page consists of several blocks: news, events, photos, etc. All objects are fetched from webservices, so no DB is used directly.

I wonder which is better:

  1. Fetch all news,photos,.. objects in DefaultController:indexAction and pass them to index.html.twig as arguments
  2. Call render(controller(News:block)) in index.html.twig. And NewsController in turn fetches objects and renders news_block.html.twig.
  3. Some other way?.. I actually use the second way but I think it is not good.

Please give me advice.

图片转代码服务由CSDN问答提供 功能建议

我用Symfony2开发大学网站。 除了我在Symfony几乎是新手。

索引页面包含几个块:新闻,事件,照片等。所有对象都是从webservices中提取的,因此不会直接使用DB。 / p>

我想知道哪个更好:

  1. 获取DefaultController中的所有新闻,照片,...对象:indexAction 并将它们传递给 index.html.twig as arguments
  2. 在index.html.twig中调用render(controller(News:block))。 并且 NewsController依次获取对象并呈现 news_block.html.twig。
  3. 还有其他方式吗?我实际上使用的是第二种方式,但我觉得它不好。 \ n

    请给我建议。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongqiaogouk86049 2015-08-21 11:55
    最佳回答

    There cannot be a perfect obsolete answer for this question. Both ways are equally standard ways of coding in Symfony. Its a decision based approach which matters a lot.

    1. Fetch all news,photos,.. objects in DefaultController:indexAction and pass them to index.html.twig as arguments -> when the data you are displaying/loading for the page is relatively less or belongs to one single module/feature. This way you have a simple process - route -> controller -> twig. Simple but sweet way of coding.

    2. Call render(controller(News:block)) in index.html.twig. And NewsController in turn fetches objects and renders news_block.html.twig. -> Use this approach when your twig/page is rendering a lot of components or requires a lot of heavy lifting in one action. This will help you a lot in maintaining the code, as each part of your twig is rendered seperately using seperate controllers. Plus, this will also improve the site UX performance a little bit, because the twig is initially rendered with bare minimum information and then each individual component renders itself seperately using own controllers.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题