For those who want to use a template var in macros without passing it around every time (symfony)
Created a Twig AppExtension Service with private $var and getter/setter
class AppExtension extends AbstractExtension
{
private $var;
public function getFunctions(): array
{
return [
new TwigFunction('setVar', [$this, 'setVar']),
new TwigFunction('getVar', [$this, 'getVar'])
];
}
public function setVar(Article $article)
{
$this->var = $article;
}
public function getVar()
{
return $this->var;
}
}
Set your var inside your template.html.twig
{% from '.../macros.html.twig' import showTitle, showImage %}
{{ setVar(article) }}
{{ showTitle('foo') }}
{{ showImage('bar') }}
You can now use getVar() to access article in macros.html.twig
{% macro showTitle(className) %}
<p class="{{ className }}">{{ getVar().title }}</p>
{% endmacro %}
{% macro showImage(className) %}
<img class="{{ className }}" src="{{ getVar().image }}"/>
{% endmacro %}
NB: may not be the most efficient solution, but works great
{{ myname }}
? – Effluvium