Jekyll/Liquid variables scopes issues

  • jekyll

Liquid is not a programming language! Take care on the use of variables…

Author
Published

When dealing with Jekyll template and use of Liquid language one may take care when assign variables, especially with several includes. Indeed, variables defined in a template (e.g. in _includes) remain defined in the parent scope. Let consider the following basic snippet code:

{% raw %}{% include templateA %}
... some stuffs...
{% include templateB %}
... other things...
use {{item}}{% endraw %}

with in templateA:

{% raw %}
{% assign item='foo'%}
{% endraw %}

and templateB:

{% raw %}
{% assign item='boo'%}
{% endraw %}

should output use boo.

This seems obvious, but in some advanced template design this must be kept in mind!

Let consider a slightly better example:

{% raw %}
{%assign collection=page.collection%}
{%assign collection_list=site.collections| where: "label", collection %}

{%for item in collection_list %}
{% assign title=item.title%}
...
{% include do-something %}
...
Use title: {{title}}
{%enfor %}
{% endraw %}
{% raw %}
...
{% assign title=page.title%}
...
{%for item in others %}
...
Another use of title: {{title}}
...
{%enfor %}
{% endraw %}

Secondly, one should take care when using forloop variables: its seems that we should avoid reassign them…