[BUG] global values (add_to_context) are missing in macro
paallaire opened this issue · comments
Expected Behavior
{{ dist }} should print ( get_template_directory_uri() . '/dist'; )
Actual behavior
{{ dist }} print nothing.
Steps to reproduce behavior
class StarterSite
public function add_to_context($context)
{
/* site */
$context['site'] = $this;
$context['env'] = wp_get_environment_type();
$context['dist'] = get_template_directory_uri() . '/dist';
$context['primary_navigation'] = Timber::get_menu('primary_navigation');
$context['secondary_navigation'] = Timber::get_menu('secondary_navigation');
return $context;
}
Macro and usage
{% macro renderIcon(name, cssClass = '', ariaHidden = 'true') %}
{% if name|default %}
<svg class="icon {{ name }} {{ cssClass }}" aria-hidden="{{ ariaHidden }}">
<use href="{{ dist }}/sprite/sprite.svg{{ '#' ~ name }}"/>
</svg>
{% endif %}
{% endmacro %}
{% set icons = ['arrow-right', 'burger'] %}
<ul class="flex flex-wrap gap-2">
{% for icon in icons %}
<li class="aspect-square w-16 border border-solid border-gray-400 flex justify-center items-center text-[64px]">
{{ ui.renderIcon(icon) }}
</li>
{% endfor %}
</ul>
Notes
How to pass "global" variables in a branch macro?
Example :
In
{{ dist }} should print ( get_template_directory_uri() . '/dist'; ) but print nothing.
What version of Timber are you using?
Timbe r2.x
What version of WordPress are you using?
6.4.2 version
What version of PHP are you using?
PHP 8.1
How did you install Timber?
Installed or updated Timber through Composer
Macros don't inherit the context. You have to pass pieces of them as parameters. Please read: https://twig.symfony.com/doc/3.x/tags/macro.html.
You could create a PHP function which you can register to Timber/Twig so you could use
get_dist()
in your macro.
Ok thank!