Hugo - Adding inline AdSense adverts

I’ve started adding a few adverts into my pages. Something I wanted to be able to achieve was adverts that appear inline in the document – a sort of mid-article ad break.

Hugo already has the concept of content summaries marked with the <!--​more​--> marker, but I wanted a bit more control: I might want the advert in a different place to the content summary split, or I might want more than one advert break.

To support this, I decided to add my own marker: <!--​advert​-->

On its own, since it’s just a comment, that won’t do anything. What we need to do is replace that text with the contents of a partial. Son in your main page processor, look for something that pulls in the main content via the following:

{{ .Content }}

…and replace it with the following:

{{ replace .Content "<!--advert-->" (partial "advert-inline.html" .) | safeHTML }}

That will replace the comment with the contents of a partial… but we haven’t defined that partial yet. Son in your layouts/partials folder, create a file called advert-inline.html. In it, put your AdSense (or other advertiser) code inside a <div> tag:

<div class="advert-inline">
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <ins class="adsbygoogle"
        style="display:block; text-align:center;"
        data-ad-layout="in-article"
        data-ad-format="fluid"
        data-ad-client="ca-pub-XXXX"
        data-ad-slot="XXXX"></ins>
    <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
</div>

Your IDs will be different to mine, of course.

I put my advert code inside a <div> so I could style it: I put some vertical space around it, and add dotted lines just to make it a bit clearer that it isn’t part of the article itself:

.advert-inline {
  margin: 6rem 0 4rem 0;
  padding: 1rem 0 1rem;
  border-top: dotted 4px #ddd;
  border-bottom: dotted 4px #ddd;
}

(That CSS will go in your “custom” CSS file – which is theme-dependent).

The inline adverts then look like the following:

Enjoy!

Pinterest
Reddit
Hacker News

You may be interested in...

Hackification.io is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com. I may earn a small commission for my endorsement, recommendation, testimonial, and/or link to any products or services from this website.

Comments? Questions?