General: Randomizing advertisements on Hugo-based Azure Static Websites

General: Randomizing advertisements on Hugo-based Azure Static Websites

I posted a while back about moving to using Hugo-based Azure Static Websites for my blog and other simple sites. One thing that I wanted to achieve is to have random advertisements for our training courses in the sidebar for the blog. You’ll see one to the right of this post.

Clearly a challenge with a static website, is how you can have random content shown. Let me tell you what I’ve done.

Source course list

In Hugo, you can have a list of data, much like a table. It can be created using JSON, YAML, CSV, and others. You can see in the image above, that I’ve chosen to make mine YAML.

In the data folder, I’ve created a file called courses.yaml and populated it with all the courses that I want to include. I included fields for title, url, image, and alt text.

Showing randomized content

Now the challenge with a static site is how to show randomized content.

One way, would be to enable javascript, and to have the client side code dynamically choose the item to be shown. If you used javascript, you could also have the advertisement change on a timer while the user is looking at the page.

I decided I didn’t want to do that, and wanted to stick with static content. I decided that what I wanted was for each page on the site, to get a random advertisement at the time it was built.

I created a widget called course_advert.html in the layouts/partials/widgets folder. In that file I put the following:

{{- $courses := site.Data.courses }}
{{- $shuffled := shuffle $courses }}
{{- $course := index $shuffled 0 }}

<div class="widget">
    <h3 class="widget-title" style="margin-bottom: 5px; font-size: 16px">
      LEARN WITH GREG
    </h3>
    <div style="border-bottom: 3px solid #E7A24A; margin-bottom: 10px; margin-top: 0px;"></div>
    <div class="widget-content" style="text-align: center;">
    <a href="{{ $course.url }}" target="_blank" rel="noopener">
      <img src="{{ $course.image }}" alt="{{ $course.alt }}" style="max-width: 100%; height: auto; border-radius: 4px; box-shadow: 0 2px 6px rgba(0,0,0,0.2);">
    </a>
    </div>
  </div>

This starts by setting a reference called $courses to the site.Data.courses table. That’s my yaml file from before. Next, I set a reference called $shuffled to a shuffled version of the data. At that point, I have it in random order. And then I set $course to the first item in the shuffled list (i.e., element zero).

Then all I needed to do was to reference this in the html. You can see the references like $course.url, $course.image, etc. in the remaining html code.

Then, every time the sidebar is built, it will display a random entry from my list.

My site is rebuilt at 1PM each day, so at that point, all pages get a new randomized advertisement.

I hope this helps someone else.

2025-07-21