shou2017.com
JP

Creating affiliate links with Hugo Shortcode

Sat Jun 22, 2024
Sat Aug 10, 2024

I previously created affiliate links using Hugo Shortcode, but when I did a minor blog renewal, I also changed the way I manage affiliate links. This new way is much better!

Here’s an old article for reference. It may not be very helpful, but just in case:

Created Amazon affiliate and other shortcodes with Hugo

The new method

Previously, I created a separate shortcode for each product, but now I manage everything with a single shortcode. Individual data is managed using Hugo’s Data.

By passing the value from data to the shortcode, you can create links for each product.

{{< affiliate dataPath="isbn4480432930" >}}

The rough flow is:

  1. Create the affiliate.html shortcode
  2. Set the value in data
  3. Pass the value from data to the shortcode (affiliate.html)
  4. Reference the value from data inside the shortcode (affiliate.html)
  5. Done!

Passing arguments to the shortcode

Use Get to pass arguments to the shortcode. Then just set it as a value.

{{ $dataPath := .Get "dataPath" }}
{{ $data := index .Site.Data.affiliates $dataPath }}
<div>
  {{ $data.Title }}>
</div>

Here, dataPath contains the path set in Hugo’s Data. This is used to retrieve the value from Data.

Compared to the old method, this is much easier. When adding a product, just add the value to Data. I wonder why I used such a troublesome method before.

And when you actually use it, it looks like this。

横井軍平ゲーム館

See Also