When using Hugo with Ezoic ads, you may want to insert ads dynamically within {{ .Content }}
,
such as after every three paragraphs, instead of manually placing them in each post.
Hugo does not provide a built-in way to achieve this, so you need a custom solution to automate the process.
There are two main ways to insert ads dynamically:
single.html
(for automatic insertion across all posts).A shortcode allows you to wrap your post content and dynamically insert ads at the specified intervals.
Run the following command to create the shortcode file:
mkdir -p layouts/shortcodes
touch layouts/shortcodes/adsense.html
adsense.html
Insert this logic inside layouts/shortcodes/adsense.html
:
{{ $adCode := `<script async src="https://your-ezoic-ad-script.js"></script>` }}
{{ $content := .Inner }}
{{ $paragraphs := split $content "</p>" }}
{{ $interval := 3 }} <!-- Insert ad every 3 paragraphs -->
{{ range $index, $paragraph := $paragraphs }}
{{ $paragraph | safeHTML }}</p>
{{ if and (ne $index 0) (eq (mod $index $interval) 0) }}
{{ $adCode | safeHTML }}
{{ end }}
{{ end }}
When writing a post in Markdown, wrap the content inside the shortcode:
{{< adsense >}}
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium.
Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.
Integer nec odio. Praesent libero. Sed cursus ante dapibus diam.
{{< /adsense >}}
This will ensure that an ad is dynamically inserted after every third paragraph within that specific post.
single.html
for Automatic AdsIf you want ads to appear automatically in every blog post, modify single.html
instead of using a shortcode.
single.html
Navigate to layouts/_default/single.html
and replace {{ .Content }}
with the following code:
{{ $adCode := `<script async src="https://your-ezoic-ad-script.js"></script>` }}
{{ $content := .Content }}
{{ $paragraphs := split $content "</p>" }}
{{ $interval := 3 }} <!-- Insert ad every 3 paragraphs -->
{{ range $index, $paragraph := $paragraphs }}
{{ $paragraph | safeHTML }}</p>
{{ if and (ne $index 0) (eq (mod $index $interval) 0) }}
{{ $adCode | safeHTML }}
{{ end }}
{{ end }}
This method ensures that all blog posts will have an ad inserted dynamically
after every three paragraphs without requiring any manual modifications.
Yes, simply change {{ $interval := 3 }}
to your desired number (e.g., 4
or 5
).
If you want automatic ad insertion, use Method 2 (Editing single.html
). If you want more control over where ads appear, use Method 1 (Shortcode).
No ad will be inserted because the condition (eq (mod $index $interval) 0)
won’t be met.