Reputation: 1949
I would like to create to separate Jekyll includes that can both reference the same common variable. Here is a simplified scenario.
I create _include/setter.html
with the following Liquid code:
{% globalString | append: include.add | append: "," %}
Then I create _include/getter.html
with the following Liquid code:
we have {{ globalString }}
Then in my page I put:
{% include setter.html add = "one" %}
{% include setter.html add = "two" %}
{% include getter.html %}
I'd like to see a result something like we have one,two,
as a result.
But of course globalString
does not exist, so this cannot work. I can't seem to create new variables in site
or page
that can be seen from includes. For now I am awkwardly working around this with capture
. Is there a better way to pass data out of an include in Jekyll?
Upvotes: 3
Views: 953
Reputation: 23952
This can be done setting the global variable before calling the includes and passing it as a parameter:
_includes/setter.html:
before: {{include.globalString}}<br>
{% assign globalString = include.globalString | append: include.add | append: "," %}
after: {{globalString}}<br>
_includes/getter.html: we have {{ include.globalString }}
Then:
{% assign globalString = "" %}
{% include setter.html add = "one" globalString=globalString%}
{% include setter.html add = "two" globalString=globalString%}
{% include getter.html globalString=globalString%}
Would output:
before:
after: one,
before: one,
after: one,two,
we have one,two,
It also works without passing the "global" variable as a parameter, the only requirement is to define it before calling the includes:
_includes/setter.html:
before: {{globalString}}<br>
{% assign globalString = globalString | append: include.add | append: "," %}
after: {{globalString}}<br>
_includes/getter.html: we have {{ globalString }}
{% assign globalString = "" %}
{% include setter.html add = "one" %}
{% include setter.html add = "two" %}
{% include getter.html %}
Upvotes: 3