I am trying to add functions to the twig gramework using twig extension.
this is the extension (I dont know if it works because I've had no opportunity to use it because of the problem I have :
class CnamtsStyleExtension extends \Twig_Extension {
protected $loader;
public function __construct(FilesystemLoader $loader)
{
$this->loader = $loader;
}
public function getFunctions()
{
return array(
'modal' => new \Twig_SimpleFunction($this, 'getModal', array('is_safe' => array('html')))
);
}
public function getModal($parameters=null) {
$template = htmlspecialchars($this->loader->getSource('component/modal.html.twig'));
return $this->getTemplateCode($template, $parameters===null ? null : json_decode($parameters));
}
protected function getTemplateCode($template, $parameters) {
$html_template = '';
if($parameters !== null) {
foreach ($parameters as $key => $value) {
$html_template = str_replace('{{' .$key. '}}', $value, $template);
}
}
return $html_template;
}
public function getName() {
return 'cnamts_style_extension';
}
}
Here is my service :
services:
cnamts.twig.cnamts_style_extension:
class: Cnamts\StyleGuideBundle\Twig\CnamtsStyleExtension
tags:
- { name: twig.extension }
arguments: ["@twig.loader"]
and the twig :
{% extends "::base.html.twig" %}
{% block body %}
Hello world
{% endblock %}
as you can see, my twig does not use any function of my extension. it is just a simple 'hello world'.
So I clear the cache (even manually to be sure), and I send the route.... I have two exceptions :
Exception number 1 in my twig:
ContextErrorException: Warning: Illegal offset type in my_project\vendor\twig\twig\lib\Twig\Environment.php line 1167
Exception number 2: even the web tool bar cannot display and there is a 500 error from the server
Illegal offset type "@WebProfiler/Collector/config.html.twig
but coming originally from the same exception in Environment.php
I am sure it is linked to the extension because when I deactivate the service I have added, there are no errors
Thank you for you help;
PS : I could debug and see that the loader is not null or whatever (it seems good)... my class is the problem because I tried to load the same service giving another class extension and I dont have the problem.
Try to use this
public function getFunctions(){
return array(
'getmodal' => new \Twig_Function_Method($this, 'getModal');
);
}