Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a variable from a Jekyll template to an include then render data with that variable?

In foo.html (a post), I have the following:

{% assign table_name="application" %}
{% include table.html %}

This assignment appears to work fine in table.html

{% assign tableName = table_name %}
<p>table name is: {{ tableName }}</p> # renders "table name is: application"

Now, I'm trying to sort through an array of data that I have defined in config.yml by doing the following:

{%  for header in site.table.tableName.headers %}
<th>{{ header }}</th>
{% endfor %}

This gives me no output whatsoever.

If I change the for statement to include the variable's content, not the variable, it works fine.

{%  for header in site.table.application.headers %}

This leads me to believe that it's not a problem with my array but that it's either a shortcoming of Jekyll, a bug in Jekyll, or I'm not accurately constructing my statements.

Any idea how I could make this work?

like image 954
imjared Avatar asked Dec 26 '22 14:12

imjared


1 Answers

Looks like this can be done. I had to think about it more programmatically. What seems to be happening is that Jekyll was expecting an object and I was feeding it a string.

{% assign tableName = "aStringName" %}
{% include table.html %}

so,

# in _includes/table.html
{%  for header in site.table.tableName.headers %}

was being interpreted as

{%  for header in site.table."aStringName".headers %}

When I switched to bracket notation for the object, it was perfect.

Final result:

{% for header in site.table[tableName].headers %}

or, as Jekyll sees it,

{% for header in site.table['aStringName'].headers %}
like image 165
imjared Avatar answered Jan 30 '23 07:01

imjared