How to access data from database?

I’m quite new to go and am currently tinkering with Hugo. I have an idea for a project which would require me to access data from a database. I’ve seen this possibility mentioned in Issue #450.

How should I tackle that best? Write an export script to write the data into a yaml (which somehow looks hacky and error prone to me) and then iterate over it or should I try to find a solution to access my DB directly? Would be grateful for every hint or piece of advice.

Not sure of a good answer, but I wanted something a little similar, which was to export data from a Drupal database to Hugo text files. I wrote a tool to do it.
https://bitbucket.org/rickb777/drupal2hugo

It currently ignores taxonomies, which is an important omission.

Rick

It’s called a STATIC site generator for a reason.

There’s an open issue about getting some “data models” support in Hugo, and one could imagine that being expanded to a database – but this is still at site build time.

If you want a more dynamic db integration, I would go the JavaScript and Rest route (maybe Firebase or similar?).

Hugo will support static data models soon… These are just YAML/JSON/TOML files in the site source directory. I could eventually see direct DB access, but it won’t be soon. There’s not much motivation for doing so since the destination isn’t dynamic, but static as @bjornerik said.

1 Like

Data models in YAML, JSON and TOML is now in Hugo master.

Pre-release-docs here:

https://github.com/spf13/hugo/blob/master/docs/content/extras/datafiles.md

1 Like

Pardon my ignorance…

Data in data/jazz/bass/jacopastorius.toml is accessible through Site, so every node can access it through that map in a template?

Is there a way to pass that map to a template? Could I, for example, assign it to Scratch and then use it in a template? The use case is “user wants to pass datasets for different artists to that template” and the artists are stored in separate files.

This should work:

{{ partial "artist.html" $.Site.Data.jazz.bass.jacopastorius }}

And in artist.html:

<ul>
{{ range .discography }}
  <li>{{ . }}</li>
{{ end }}
</ul>

You could also add it to Scratch … But it shouldn’t be needed.

Not sure about the Jaco Pastorius example being soo clever, but …

1 Like

But what you probably want to do in this case (I have tested it and will adjust my example in the docs).

Given a folder with a lots of bass players, each with its own discography etc (a new bass player? just add a new file).

{{ range $.Site.Data.jazz.bass }}
{{ partial "artist.html" . }}
{{ end }}

And in artist.html:

<ul>
{{ range .discography }}
  <li>{{ . }}</li>
{{ end }}
</ul>
1 Like

Note this: