Search code examples
htmlgeneratormiddlemanhugo

Auto-generated pages in Hugo


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?


Solution

  • Along the lines of the documentation, I achieved the MVP in the following steps:

    1. Installed a test Hugo site, hugo new site carsite.
    2. Root folder already had /data/ folder, I created cars subfolder there.
    3. 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).
    4. Create content files inside /data/ folder:

      ford.yml:

      Name: "Ford"
      Color: "Blue"
      

      and

      cadillac.yml:

      Name: "Cadillac"
      Color: "Pink"
      
    5. Create a partial to style the car listing:

      carsite/themes/<your theme name>/layouts/partials/car_listing.html

      <li>{{ .Name }} in {{ .Color }}</li>
      
    6. 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):

    Hugo Data files-driven pages


    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