A helpful Twig extension – Fetch

twig

Inspired by Symfony’s twig extension to fetch output from external controllers and URL’s in their Twig subsystem, I wrote this small Twig function which you can use in your general twig templates. The main purpose of this extension is to fetch external URL (via GET or POST). You can also pass an arbitrary number of parameters which is helpful while fetching external URL via POST.

Here is the code of the Fetch extension.

https://gist.github.com/hasinhayder/9705763

To use this newly created extension, initialize your Twig loader in this way

[sourcecode language=”php”]
//include the twig extension file first

$loader = new \Twig_Loader_Filesystem(__DIR__ . "/../app/twig"); //change accordingly
$twig = new \Twig_Environment($loader);
$twig->addExtension(new Fetch());
return $twig;
[/sourcecode]

And then you can simply call it in your twig files in this way

[sourcecode language=”php”]
{{ fetch("http://yourdomain.tld") }}

//or

{{ fetch("http://yourdomain.tld", {‘param1′:’value1′,’param2′:’value2’}) }}
[/sourcecode]

And you’ll notice that the output from the URL is now fetched and displayed in your twig output 🙂

Hope you enjoy this 🙂