Reputation: 79
I have a data folder structure:
_data/footer/1.yml
_data/footer/2.yml
etc
What I want to do is within the template, based on the front matter variable is to, select one of those files and return the data contained in them.
If I do this:
site.data.footer.1
it returns the data withn 1.yml. If I try to do site.data.footer.{{page.footer}}
it returns nothing, even if the front matter has the footer variable set to 1 like this:
---
footer: 1
---
{% assign foot_id = page.footer %}
{{foot_id}}
{% assign stuff = site.data.footer.{{foot_id}} %}
{{stuff}}
stuff
in this case would be blank. Is this the correct way to do this? Whats going wrong?
Upvotes: 3
Views: 1072
Reputation: 52809
If we look at your datas :
site.data.footer = {"1"=>{"variable"=>"one"}, "2"=>{"variable"=>"two"}}
we have a hash were keys are strings.
We can access our datas like this :
{{ site.data.footer.1 }} => {"variable"=>"one"}
or
{{ site.data.footer["1"] }} => {"variable"=>"one"}
Note that the bracket notation takes a string as key. If you try with an integer, it returns nothing {{ site.data.footer[1] }} => null
.
If we want to use a page
variable, we need it to be a string. It can be :
---
# a string in the front matter
footer: "1"
---
{{ site.data.footer[page.footer] }} => {"variable"=>"one"}
or an integer casted to string
---
# a string in the front matter
footer: 1
---
Transform an integer to a string by adding it an empty string
{% assign foot_id = page.footer | append: "" %}
{{ site.data.footer[foot_id] }} => {"variable"=>"one"}
Note: you can also cast a string to an integer like this :
{% assign my_integer = "1" | plus: 0 %}
{{ my_integer | inspect }} => 1 but not "1"
Upvotes: 7