Are you using Hugo the static site generator? Often it can be desireable to reuse a particular section across several pages, blog posts or articles. This is how we configured our ad segment at the bottom of some of our articles.

Show me how

In your sites layouts/ directory, add a shortcodes/ directory. You can also add additional subdirectories for organizational purposes.

We chose to use layouts/shortcodes/ads/photoroll.md for our Photoroll ads, for example. The shortcode file type can be either markdown or html but we found markdown easier to work with, without being less flexible since it is a superset of html.

Now, adding an ad at the end of a blog post becomes as easy as using the follwing shortcode markup:

{{< ads/photoroll >}}

Here is the contents of the file that our ads shortcode refers to:

layouts/shortcodes/ads/photoroll.md

{{ partial "adbreak.html" . }}

<div>
  <a style="width: 160px; float: right; margin-left: 10px" href="https://apps.apple.com/us/app/photoroll-media-transfer/id1629728137" target="_blank" alt="Get it on the App Store"><img src="/appstore-2x-transparent.png" /></a>

  <p><i>Need private photo sharing that's not tied up in the social media circus?</i> <a href="https://photoroll.app/" target="_blank">Photoroll</a> is a good way to share photos with your clients.<br/>Or privately gather media from participants of weddings and other small to medium-sized events.</p>
</div>

The rendered article would now contain a segment looking like this:

Shortcodes inside shortcodes, partials inside partials

We also chose to further break out some parts that are reusable across multiple ads into a partial. In this case just a simple divider and headline, but the complexity it could encapsulate neatly could be far greater than this:

layouts/partials/adbreak.html

<br />
<br />
<hr />
<strong>sponsor</strong>

When partial and when shortcode? They have slightly different feature sets regarding inputs and capabilities. Shortcodes are probably more end-user friendly in the way they look and accept input parameters, should you need those. Partials have an awkward dot in their syntax. Hence we settled for shortcodes for the outermost level, the ones actually used in our articles.

Let’s render it for real in this article

The rendered ad example above was a png to preserve its contents across time and varying screens, but here’s a dynamically rendered example to finish off this article:

(well… as dynamic as can be for a static site. Dynamic at site generation time at least.)




sponsor

Need private photo sharing that's not tied up in the social media circus? Photoroll is a good way to share photos with your clients.
Or privately gather media from participants of weddings and other small to medium-sized events.