Clone: git clone https://github.com/CloudCannon/hugo-learn-blog-template.git
Starter branch: git checkout data-intro-start
Finished lesson: git checkout data-intro-finish
What “data” is in Hugo
How to create and structure data
Practical use case for data
In the world of static sites/Jamstack, there is - by design - no database you can query directly. However, having access to supplemental data is still something that many people might still want. Naturally, you can put data into front matter, but sometimes it’s nice to have the flexibility to have it available from anywhere across your site.
This is where data files come in. A data file acts as a mini database that stores information, which Hugo gives you easy access to through simple conventions.
Additionally, Hugo has built-in functions to get data (in forms such as JSON and CSV) from external sources, such as APIs. Here, we’ll simply focus on data files local to your site.
Fortunately, there isn’t too much to set up or even learn conceptually when it comes to data, so we can get straight into using it.
data. Hugo knows to look for this.
staticfolder, move the
staff.ymlfiles into this folder. YAML, TOML, or JSON are all acceptable formats, we’ll use YAML here because it’s more human-readable.
Depending on your setup/code scope, you might need to use $.Site to refer to global scope.
To make things easier, a few things have already been set up:
shortcodes/map.html with the following contents:
Finally, add the map shortcode to the
content/locations.md page, below the front matter:
Simple as that! When we view the
/locations page in the browser, we should see a map with some markers on it. We can easily add more markers to the data file and it will be populated when Hugo next builds the site.
Another potential use for data is information about people, such as employees, conference attendees, or contacts.
One thing that might make sense in our case is to provide staff contact details for sightings of rare birds. Any new locations could then be added to the
locations.yml file. We already have
staff.yml in our data folder, with some simple contents (randomly generated names and a placeholder image location). As before, let’s create a shortcode for the situation, which we will use in our locations and about pages.
shortcodes/staff.html and add this content:
This will generate a very basic block containing staff names and placeholder images. We can also change the title of the block if we want.
Next, add the following to
This will output all of our staff information, including names and images. If we want to add more information or more staff, such as social media, it is now much easier to manage.