Back to Online Portfolio

Changelog

Site optimization and bugfixes

June 8, 2023

web hugo

Improving loading time with Hugo image processing

I used Hugo’s image processing features to have all the images on my website compressed. The basic shortcode I came up with finds any global asset (stored in /assets instead of /static) or an asset in a page bundle. If you want to use a page bundle resource, make sure to pass in the $.page variable

{{ $image := ""}}
{{ with $.page }}
    {{- $image = $.page.Resources.GetMatch $.src -}}
{{ else }}
    {{- $image = resources.Get $.src -}}
{{ end }}

{{ with $image }}
    {{ $image = $image.Resize $.resize }}
    <img
        {{ with $.class}} class="{{ $.class }}" {{ end }} 
        {{ with $.id }} id="{{ $.id }}" {{ end }}
        title="{{ cond (isset .Params "alt") $.alt $.caption}}"
        src="{{ $image.RelPermalink }}"
    />
{{else}}
    <h1> image not found :(</h1>
{{ end }}

This example retrieves the global asset “portrait2.png” with the following directory structure.

assets/images/
├── face.png
├── portrait2.png
└── portrait.png
{{ partial "imgc" (dict 
    "id" "portrait" 
    "src" "images/portrait2.png" 
    "resize" "1000x webp photo q50"
)}}

This example retrieves an image at the same level as an index.md or _index.md.

Fake “Primary Keys” in Hugo

These logs have different IDs that are all over the place
These logs have different IDs that are all over the place

Hugo does not have any kind of ID system, which makes implementing the unordered “log id” feature on my journeys page unnecessarily difficult. If you were using a backend, it would be as simple as sending a query SELECT * FROM Logs WHERE Project="<project id>" and iterating through the IDs of the results.

I couldn’t find a better solution than iterating through every page, assign it an index, and cross reference the logs to display with their id. The code in my partial ended up looking like this

{{ $indexed_logs := slice }}
{{ range $index, $log := $.all_logs.ByDate}}
  {{ if (in $.log_subset $log )}}
    {{ $indexed_logs = append $indexed_logs (slice (dict "log_number" $index "log" $log)) }}
  {{ end}}
{{ end }}

$.all_logs is a variable passed into the shortcode for all the logs. While $.log_subset are the logs we are trying to display. This code essentially appends {"log number": <index>, "log": <Page>} to a list if $log is going to be displayed.

The Future

I’m hoping to improve my SEO for my posts. I haven’t added any meta tags to anything yet.