Use data files to import existing data or have an easy way of managing global data in this Hugo tutorial.
A data file in Hugo is sort of like a read-only database. The way it works is you can put JSON, CSV, YAML, XML, or TOML files in a directory called
data, then access that data in a layout using
.Site.Data. You can also download JSON or CSV files from an external source on build if you want to get fancy.
First we’ll create a data file with all of your favorite vacation spots. Create
/data/vacation_spots.yml with the following content:
To list your favorite vacation spots, you’re going to need:
We could put all of this in a content file, but it’s going to be far more complicated than the simple markdown we have there currently. And what if we wanted to use this map again on another page? That’s a lot of HTML to copy and paste around.
You’ll create a shortcode which can be used in any content file to create a map with marked locations. Let’s see how it works.
Create a directory called
/layouts/ and add a file called
vacation_spots.html with the following content:
There are a few things going on here, so let me explain:
/map.jswhich we’ll create shortly. This is responsible for initializing the map and adding the markers.
/static/map.js with the following content:
The final set is to actually use the shortcode. Open up
/content/about.md and append the following:
Open it up in a browser and admire all your hard work.
This is only the beginning of your Hugo journey. You now have the skills to build a basic Hugo site. To continue the journey there’s a few resources I recommend:
Finally I want to quickly mention CloudCannon - it’s a content management system with first class support for Hugo and syncs directly with your Git repository. So your developer team can continue working in Hugo while your content team can manage the content on the site. It’s the best of both worlds.
Thanks for reading and Happy Hugoing!