I'm getting prices and bookings from different sources in one flat booking table like this:
record 2014-06-07 2014-06-14 2014-06-21 2014-06-28
1 2000.00 2500.00 2500.00 3000.00
array(3) array(null) array(2) array(1)
2 3000.00 3500.00 3500.00 2800.00
array(null) array(1) array(null) array(null)
Now I need to render the columns with prices and bookings into a nice layout. So I wrote a custom twig extension and gave them prices and bookings as arguments.
So my question is: How can I render the result of the custom Twig_Function within the twig extension? Sometimes I need to render only the price and sometimes I need to render the price and 3 bookings within a week.
Before using the twig extension I tried to render a custom controller. But that was very slow because having lots of rows and columns in the table.
First it did not worked for me, because I was getting a circularReferenceException. I helped me with injection an existing Twig Enviroment. So my service definition looks like
app.twig.extension:
class: App\AppBundle\Twig\AppExtension
arguments: ["@twig"]
tags:
- { name: twig.extension }
An the constructor looks like this:
function __construct(\Twig_Environment $environment)
{
$this->environment = $environment;
}
In the function then I use
public function myFunction()
{
// logic...
return $this->environment->display(extension, arguments)
}
Inject in you twig extension templating service. See example.
Your code will look like this:
use Symfony\Bundle\TwigBundle\Debug\TimedTwigEngine;
class MenuExtension extends \Twig_Extension
{
/**
* @var TimedTwigEngine
*/
private $templating;
function __construct(TimedTwigEngine $templating)
{
$this->templating = $templating;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('app_prices_bookings', [$this, 'pricesBookings'], ['is_safe' => ['html']]),
];
}
public function pricesBookings($prices, $bookings)
{
$this->templating->render('@App/App/prices_bookings.html.twig', $prices, $bookings);
}
}
app/config.yml:
app.twig.extension:
class: App\AppBundle\Twig\AppExtension
arguments: ["@templating"]
tags:
- { name: twig.extension }
And now you can use this function in twig:
{{ app_prices_bookings(prices, bookings) }}