3

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?

asked Apr 4, 2016 at 15:18

1 Answer 1

7

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"
answered Apr 5, 2016 at 9:47
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.