General: Prioritizing random adverts on Hugo-based Azure Static Websites
I posted a while back about being able to have random advertisements for our training courses in the sidebar for my blog. You’ll see one to the right of this post.
That has been working great, and every time I do a new build (each day), each page ends up with a random course advertisement.
Priorities
What I’ve now decided though, is that I didn’t want all the courses to show up with the same frequency. I wanted to assign a priority to each one, from 1 to 10.
So, in my courses.yaml file that’s in the data folder, I added a priority value to each course. You can see that in the image above.
Showing randomized content based on priorities
The next challenge was to show the adverts in my widget, based on the priorities.
Note that I could have enabled javascript, and to have the client side code dynamically choose the item to be shown. And if I’d done that, I could also have had the advertisement change on a timer while the user is looking at the page. I still decided I didn’t want to do that, and wanted to stick with static content.
I decided to stick with the idea that each page on the site would get a random advertisement at the time it was built.
I modified the widget as follows:
{{- $courses := site.Data.courses }}
{{- $weighted := slice }}
{{- range $courses }}
{{- $course := . }}
{{- $priority := .priority | default 5 | int }}
{{- if gt $priority 0 }}
{{- range seq $priority }}
{{- $weighted = $weighted | append $course }}
{{- end }}
{{- end }}
{{- end }}
{{- if gt (len $weighted) 0 }}
{{- $shuffled := shuffle $weighted }}
{{- $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 }}" loading="lazy"
style="max-width: 100%; height: auto; border-radius: 4px; box-shadow: 0 2px 6px rgba(0,0,0,0.2);">
</a>
</div>
</div>
{{- end }}
This still starts by setting a reference called $courses to the site.Data.courses table. That’s my yaml file from before.
I’ve then calculated a weighted priority for a page, based on the priority of each course. I added two extra rules. The first says that if the priority isn’t there, it will default to 5. The second rule says that if the priority is zero, that the course will be ignored. (That will let me set up courses pre-release and not have them shown).
Finally, as long as at least one course has a priority (i.e., they aren’t all zero), then I’ll shuffle them and pick the first one after they are shuffled.
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-11-05