Hey,
I’m working on a project where I would like to have a totally automatic layout. The content is in data
files. For each page it’s exactly the same layout, with a for
. The idea would be to have something like {% for item in site.data.{{ page.name }} %}
in the page layout. How could this be done?
Thanks!
You should be able to treat site.data
as an array, so try: site.data[page.name]
Thank you, but it didn’t work. I have this error:
Liquid Warning: Liquid syntax error (line 47): Expected id but found open_square in "item in site.data.[page.name]" in ...
The square-bracket notation replaces the dot-notation (i.e. site.data
is site['data']
), so try dropping the second dot. I.e.:
{% for item in site.data[page.name] %}
1 Like
Same problem… But I just did it another way, with the content in the post and not the data
what is the error now that the syntax error is fixed?
I’d also leave out the for and break it down
make sure you understand this. Like if it has an extension in it. e.g. foo.md
{{ page.name }}
Then setup you data YAML file.
foo.md.yaml
I think this may cause issues with the dot next so rather make one data file used by all your pages.
_data/foo.yml
a: []
b: []
Then you can do this. Note foo is the YAML file name above
{{ site.data.foo.a }}
{{ site.data.foo["a"] }}
{{ site.data.foo[page.name] }}
You can avoid file extension in the value of name (and therefore YAML key) by using a filter to get base name without extension . Then use that as your lookup
If every page has it’s own data then I’d say why have a data file when you can keep it all in the md file.
foo.md
---
title: Foo
authors: [ 'fizz', 'buzz']
---
{{ page.authors | jsonify }}
And if all pages have the same key such as authors then you can move all your markdown out the pages so they are just frontmatter and then use page.authors in a layout shared by each page.
I suspect the problem @JulSeb42 ran into is that data files can’t have periods in their name. For example, if you tried to setup a paired mypage.md
and mypage.md.json
, all attempts to access the data will fail with nil because of the period. (tested code):
File |
Contents |
_data/mypage.md.json |
{"a": 1, "b": 2} |
mypage.md |
{{ site.data[page.name] | inspect }} |
|
{{ site.data['mypage.md'] | inspect }} |
|
{{ site.data.mypage.md | inspect }} |
Output: nil nil nil
One could strip the extension from page.name
and name the data file mypage.json
, but as @MichaelCurrin pointed out, it is easier to just include data in a page’s front-matter.