I have a Twig extension in my Symfony project which renders a twitter widget. Currently, in my extension, I have this:
public function twitter($handle, $number = 5)
{
return "<div data-tweet-row=\"<div><a href='http://twitter.com/{screen_name}/status/{id}'>{tweet}</a><span class='datetime'>{datetime}</span></div>\" data-twitter-header=\"<div class='header'><img src='https://api.twitter.com/1/users/profile_image?screen_name={screen_name}&size=normal' /><h4><a href='http://twitter.com/{screen_name}'>@{screen_name}</a></h4></div>\" id=\"twitter\"> </div><script>$('#twitter').biff_twitter({screen_name:'$handle',count:$number});</script>";
}
However I really don’t like this solution, I’d rather have the HTML saved under views and then load the file from within my extension.
I have access to the container from within the extension using:
private $container;
public function __construct(ContainerInterface $container){
$this->container = $container;
}
So I need something like
$view_file = $this->container->get('...')->view('InternalSocialBundle:twitter_placeholder.html.twig')
Ok, so I resolved the issue that I had but it was sort of my fault for not testing this fully. @Cyprian’s solution does indeed work absolutely fine when you’re not doing anything complicated and just using the extension as intended.
My problem was that I was using this evaluate extension which was loading a template from the database, therefore it was twig that was doing all of the loading (and therefore was only interpreting the first param of
$this->render()as astring– it made no attempt to load it using the symfony naming pattern).This means my extension would work fine when using the above method in an actual twig file, but not when I used the
{{body|evaluate}}extension.The solution to this problem was as follows:
In my services.yml file, not only did I need
service_container, but alsotwig.loaderso it looked something liked:I then have this as the twig extensions constructor:
In my
getFilters()definition:and finally, before I returned the rendered output:
This ensured that I was always using the
\Symfony\Bundle\TwigBundle\Loader\FilesystemLoaderloader, and not\Twig_Loader_Stringwhich was being used in my case.