Takes a view to apply when rendering content jau.

Začiatočník

Sprievodca kryptomenami pre začiatočníkov

Stredne

Stredne pokročilý sprievodca kryptomenami

Expert

Správy o kryptomenách pre expertov

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.

How to create and access data

  • In the root of your project, simply create a folder called data. Hugo knows to look for this.
  • From the static folder, move the locations.yml and staff.yml files into this folder. YAML, TOML, or JSON are all acceptable formats, we’ll use YAML here because it’s more human-readable.
  • Then, anywhere in your layouts or shortcodes, you can access the data:

copied

.Site.Data.<filename without extension>

Depending on your setup/code scope, you might need to use $.Site to refer to global scope.

Use case 1 – location map

A classic use case for data on a static site is in an interactive map. We’ll do exactly this with OpenStreetMap and Leaflet because it’s very easy to set up and you don’t need an API key.

To make things easier, a few things have already been set up:

  • Imports for Leaflet’s JS and CSS in the head of baseof.html
  • static/map.js ****with the necessary JavaScript code for working with Leaflet and OpenStreetMap. This isn’t the focus of the lesson, but feel free to look at it/modify it.
  • A basic content file: content/locations.md.

Now all we need to do is use our global data with our JavaScript map code. To do this, let’s create another shortcode to render the map. Create shortcodes/map.html with the following contents:

shortcodes/map.html

copied

<div id="map-canvas"></div>
<script>
  let markers = {{ $.Site.Data.locations }};
</script>
<script src="/map.js"></script>

Finally, add the map shortcode to the content/locations.md page, below the front matter:

content/locations.md

copied

# Endangered bird locations
{{< map >}}

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.

Data use case 2 – list of staff

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.

First, create shortcodes/staff.html and add this content: dsfggsdfgsfdgsfdgsfdg

Začiatočník

Sprievodca kryptomenami pre začiatočníkov

Stredne

Stredne pokročilý sprievodca kryptomenami

Expert

Správy o kryptomenách pre expertov