mickburkejnr
mickburkejnr

Reputation: 3690

How To Include PHP Files In Twig Files In Symfony2

I am trying to insert a latest tweets "widget" on to a Symfony2 project. I have found an ideal script written in PHP that will do the job perfectly.

However, I don't know where the best place to put 3rd party PHP files in a Symfony2 project. I have placed them in the same folder as all my twig files reside, changed the name to read tweets.php.twig, and even located them in the web folder. When I try to include the file in the twig file that needs the Twitter feed it comes up with an error saying that it can't find the file.

Do I have the right idea, or do I have to convert the PHP in to a twig file or write the PHP script in to a controller?

Upvotes: 2

Views: 4826

Answers (1)

Jason
Jason

Reputation: 46

I believe the recommended way would be to create a Symfony2 bundle that encapsulates all the logic for the tweet widget. You would then call your bundle controller and pass the response to your twig template.

If that is too complicated or you want something more quick and dirty - you can create a controller like TweetWidgetController.php and put the code into there as an action like widgetAction. Just make sure you return the tweet widget output in a Symfony response object.

Then from your main controller - you can do something like

$widget = $this->forward('YourBundle:TweetWidget:widget', array('twitterid' => 'yourtwitterid'));

return $this->render('YourBundle:yourtemplate.html.twig',array('widget' => $widget->getContent()));

Now in your twig template you can put it wherever you'd like by referencing it as:

{{ widget }}

Upvotes: 3

Related Questions