0

I'm pretty new to patternlab and am just migrating my php based project onto the node version. I am having issues to access global data and block in a block file, which I didn't have previously.

I am using Pattern Lab Node v3.0 on Mac, with Node v13.9.0, using a Gulp Edition with Twig.

source/_data/data.json

"img": {
    "landscape": {
      "w_1024": {
        "src": "../../images/1536x864_16x9.jpg",
        "alt": "16x9 Image"
      }
    }
  }

source/macros/ui.twig

{% macro icon( name ) %}
  {% if name == "airplay" %}<img src="airplay.png"/>{% endif %}
{% endmacro %}

source/02-organisms/00-global/file-1.twig

{% import "@macros/blocks.twig" as blocks %}
{% import "@macros/ui.twig" as ui %}
<p class="icon">{{ ui.icon( "airplay" ) }}</p>
<p class="output">{{img.landscape.w_1024.src}}</p>
{{ blocks.media(item) }}

source/macros/blocks.twig

{% import "@macros/ui.twig" as ui %}
{% macro media( params ) %}
<p class="icon2">{{ ui.icon( "airplay" ) }}</p>
<p class="output2">{{img.landscape.w_1024.src}}</p>
{% endmacro %}
Expected Behavior

Generated html should look as follow :

<p class="icon"><img src="airplay.png"/></p>
<p class="output">../../images/1536x864_16x9.jpg</p>
<p class="icon2"><img src="airplay.png"/></p>
<p class="output2">../../images/1536x864_16x9.jpg</p>
Actual Behavior

Generated html looks as follow :

<p class="icon"><img src="airplay.png"/></p>
<p class="output">../../images/1536x864_16x9.jpg</p>
<p class="icon2"></p>
<p class="output2"></p>

Any help is welcome!

Harry
  • 321
  • 2
  • 12

1 Answers1

1

Macro's have their own variable scope. If you want to access any other defined variables you'd need to pass the special variable _context.

{% macro foo(bar, context) %}
    {{ bar }}
    {{ context['foo'] }}
{% endmacro %}

{% import _self as macros %}

{{ macros.foo(42, _context) }}

demo - demo with include

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • Oh that seems to do the trick, thanks! I guess there is no way to implicitly call _context for macro foo? – Harry Feb 25 '20 at 13:14
  • No, you have to explicitly pass the variable – DarkBee Feb 25 '20 at 13:22
  • Ok! Last question: how do you access a global var in an include which is in a macro? I don't want to use `with` since I'm trying to define a default value in my include (either the `with` or default to global var) – Harry Feb 25 '20 at 14:28
  • the variable `context` u've passed in the macro will be accessible inside the include so writing `{{ context['my_var'] }}` should work. See updated demo – DarkBee Feb 25 '20 at 14:31
  • Thanks a lot DarkBee! – Harry Feb 25 '20 at 14:36