Is it possible to auto-generate pages from a data file in Hugo, like in Middleman? I have a yaml file cars.yml
which looks like this:
---
- name: "Ford"
color: "blue"
- name: "Cadillac"
color: "pink"
and would like to auto-generate a separate page for each car record in the datafile based on a predefined template. How can I do that?
Along the lines of the documentation, I achieved the MVP in the following steps:
hugo new site carsite
./data/
folder, I created cars
subfolder there.carsite/data/cars
will hold each car as a separate file. This differs from your original plan to put them in a list, but one-file per one-car approach is better (version control, maintenance, less error-prone because erroneous .yml will be flagged separately, not monolithic data file).Create content files inside /data/
folder:
ford.yml
:
Name: "Ford"
Color: "Blue"
and
cadillac.yml
:
Name: "Cadillac"
Color: "Pink"
Create a partial to style the car listing:
carsite/themes/<your theme name>/layouts/partials/car_listing.html
<li>{{ .Name }} in {{ .Color }}</li>
Call the loop, or in Go terminology, range data files in the file, responsible for your chosen location. For example, let's output it on the main homepage, which is controlled by carsite/themes/<theme name>/layouts/index.html
:
...(existing header.html partial and so on)...
<ul>
{{ range $.Site.Data.cars }}
{{ partial "car_listing.html" . }}
{{ end }}
</ul>
...(existing footer.html partial and so on)...
Here's how it looks on mine (ghostwriter template):
If you insist on housing all the files within one data file, that should be doable too, just query the data file and range it. Also, if you chose yml
format, set the correct format sequence of your data file (your proposed data structure looks suspicious since the list is straight in the root, instead add a key, for example, cars:
as per aforementioned YML spec):
carsite/data/cars.yml
cars:
- Name: Ford
Color: Blue
- Name: Cadillac
Color: Pink