4

I want to know which is the best approche between rendering a controller in twig or use a macro. For exemple we have a page where we render a post with his comments.

  • In one hand we can load the comment in the controller that shows the post and pass it as an argument to a twig macro to rendre the list of comments
  • in the other hand we can create a controller that take the post as an argument and render it the twig that shows the post

Which one is the best approche? i am using symfony2

Ramy Rais
  • 140
  • 2
  • 10

2 Answers2

2

I would say that the first option of building a macro to handle the display would be a little better given the details that you provided.

Here's why:

By passing the comments in with the post to the Twig template, everything is encapsulated and appears logical when viewing the template (as a developer). That particular Twig template handles all of the layout for that page and since the list of comments is related to the content it is logical that the template would simply loop through the comments and use a macro to display each item. The controller should also be simple as it just queries the database for the comments and then passes them to Twig. Another benefit is that the macro could also be easily re-used on other pages. While the controller could be reusable as well, it would likely be less easily so.

The main caveat with this approach is that if you have to do much logic with getting the comments, then it would be better to create a new controller to avoid cluttering the main one up.

One main use case where it would be better to pass the post as an argument to a separate controller would be if you desire to only show the comments to certain users. This would allow the controller to determine if the user was allowed to view the comments and then return them to a Twig template and display them if so. While Twig could theoretically do this, it seems better to keep that in the controller.

bassplayer7
  • 924
  • 1
  • 13
  • 38
0

Better use TwigExtension, define a function which fetches comments. Also there are some posts abount performance issues of rendering a controller...

Community
  • 1
  • 1
xurshid29
  • 4,172
  • 1
  • 20
  • 25