How to add AdSense to Hugo and Eleventy sites with partials and shortcodes
Key takeaways
- In Hugo, the AdSense code belongs in a partial called from the base template head, and ad units fit in a shortcode stored in layouts/_shortcodes.
- hugo.IsProduction is false when you run hugo server and true for hugo build unless you set another environment, which makes it a simple guard against development ad requests.
- Hugo copies the static directory to the public output, so static/ads.txt is served at /ads.txt.
- In Eleventy, addShortcode registers an ad unit shortcode usable in Nunjucks, Liquid and Markdown, because Markdown is pre-processed as Liquid by default.
- Eleventy passthrough copy paths are relative to the project root, and a file inside the input directory is copied without the input directory prefix.

In Hugo, put the AdSense code in a partial included in your base template’s <head>, and wrap ad unit code in a shortcode you can drop into Markdown. In Eleventy, do the same with a layout include and addShortcode. Guard both with an environment check so local servers do not request ads, and ship ads.txt through Hugo’s static/ folder or Eleventy’s passthrough copy.
Both generators output plain HTML, which is exactly what Google’s instructions assume: the AdSense code between <head> and </head> on every page (Where to place AdSense code in your HTML), ad unit code in the <body>. The snippets below use ca-pub-0000000000000000 and slot 1234567890 as placeholders.
Hugo
The examples follow current Hugo documentation (v0.170 at the time of writing), which stores partials in layouts/_partials/ and shortcodes in layouts/_shortcodes/. If your theme still uses layouts/partials/ and layouts/shortcodes/, keep the theme’s structure.
Step 1: store the publisher ID in site params
In hugo.toml:
[params]
adsenseClient = "ca-pub-0000000000000000"
Step 2: create the head partial
{{/* layouts/_partials/adsense-head.html */}}
{{ if and hugo.IsProduction site.Params.adsenseClient }}
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client={{ site.Params.adsenseClient }}" crossorigin="anonymous"></script>
{{ end }}
Hugo’s hugo.Environment docs state that the environment is “development when you run the hugo server command, and production otherwise”, unless you pass --environment or set HUGO_ENVIRONMENT. hugo.IsProduction therefore keeps ad requests out of your local preview.
Step 3: call the partial from the base template
{{/* layouts/baseof.html (or your theme's base template) */}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
{{ partial "adsense-head.html" . }}
</head>
<body>
{{ block "main" . }}{{ end }}
</body>
</html>
That is enough for Auto ads. For manual placements, continue.
Step 4: create an ad unit shortcode
Per Hugo’s shortcode docs, shortcode templates live in layouts/_shortcodes/ and read arguments with .Get.
{{/* layouts/_shortcodes/adsense.html */}}
{{ if hugo.IsProduction }}
<div class="ad-slot">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="{{ site.Params.adsenseClient }}"
data-ad-slot="{{ .Get "slot" }}"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
{{ end }}
Call it from any Markdown file:
Intro paragraph.
{{< adsense slot="1234567890" >}}
Rest of the article.
Use the standard notation {{< >}}. Hugo’s shortcode usage docs explain that standard-notation output is merged into the page “after Markdown rendering”, while Markdown notation {{% %}} is processed before the Markdown renderer runs. Ad code should not go through Markdown.
Step 5: place ads in list templates (in-feed)
For a feed of posts, insert the unit inside the range loop at a fixed interval. This mirrors Google’s in-feed advice to place the code between items of the feed:
{{ range $i, $p := .Pages }}
<article><h2><a href="{{ $p.RelPermalink }}">{{ $p.Title }}</a></h2></article>
{{ if and hugo.IsProduction (eq (mod (add $i 1) 4) 0) }}
{{ partial "adsense-infeed.html" . }}
{{ end }}
{{ end }}
adsense-infeed.html would hold the in-feed code generated by AdSense. The in-article, in-feed and Multiplex guide explains the differences between those units.
Step 6: ads.txt in Hugo
Hugo’s directory structure docs describe static/ as files “copied to the public directory when you build your project”, with robots.txt as an example. Create static/ads.txt:
google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0
Eleventy
The examples use Eleventy 3 with an ESM config file (eleventy.config.js), input directory src and output _site. CommonJS configs work the same with module.exports.
Step 1: expose an ads flag to templates
Eleventy’s environment variables are available in JavaScript files evaluated at build time; to use them in other template languages, the docs suggest a JavaScript data file. Eleventy also sets ELEVENTY_RUN_MODE to build, serve or watch.
// src/_data/ads.js
export default {
client: "ca-pub-0000000000000000",
enabled:
process.env.ELEVENTY_RUN_MODE === "build" &&
process.env.ADS_ENABLED === "true",
};
Set ADS_ENABLED=true only in your production build settings, so local builds and previews stay ad-free.
Step 2: add the head snippet to the base layout
<!-- src/_includes/base.njk -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
{% if ads.enabled %}
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client={{ ads.client }}" crossorigin="anonymous"></script>
{% endif %}
</head>
<body>
{{ content | safe }}
</body>
</html>
Step 3: register an ad unit shortcode
Eleventy shortcodes added with addShortcode are available in Markdown, Liquid, Nunjucks and JavaScript templates, and return a string.
// eleventy.config.js
export default function (eleventyConfig) {
const enabled =
process.env.ELEVENTY_RUN_MODE === "build" &&
process.env.ADS_ENABLED === "true";
eleventyConfig.addShortcode("adsense", function (slot) {
if (!enabled) return "";
return `<div class="ad-slot">
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-0000000000000000" data-ad-slot="${slot}" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
</div>`;
});
eleventyConfig.addPassthroughCopy("src/ads.txt");
}
export const config = {
dir: { input: "src", output: "_site" },
};
Use it in Markdown or Nunjucks:
Intro paragraph.
{% adsense "1234567890" %}
Rest of the article.
Eleventy’s docs note that Markdown files are pre-processed as Liquid by default, so the shortcode works in .md files. The returned HTML then goes through the Markdown parser. Keep it as one block with no blank lines inside, and leave a blank line before and after the shortcode call.
Step 4: ads.txt in Eleventy
Eleventy only copies what you tell it to. The passthrough copy docs state that paths are relative to the project root and that, when the file sits inside the input directory, “the input directory will be stripped from the output path”. addPassthroughCopy("src/ads.txt") (already in the config above) therefore produces _site/ads.txt.
Reserve space for the shortcode output
Both shortcodes wrap the unit in <div class="ad-slot">. Give that class a minimum height in your main stylesheet, so content below the ad does not jump when it loads:
.ad-slot { min-height: 280px; margin: 2rem 0; }
@media (min-width: 768px) {
.ad-slot { min-height: 250px; }
}
The values are starting points; match them to the sizes that usually serve in your layout. A wrapper with min-height is your own markup, not part of the ad code, and it lets taller ads grow instead of being clipped. The CLS guide explains how to choose them and when exact CSS sizes per breakpoint are a better fit.
How do I place an ad after the Nth post in Eleventy?
Nunjucks exposes loop.index (starting at 1) inside a for loop, which plays the role of the counter Google’s in-feed instructions ask for:
{% for post in collections.posts %}
<article><h2><a href="{{ post.url }}">{{ post.data.title }}</a></h2></article>
{% if ads.enabled and loop.index % 4 == 0 and not loop.last %}
{% include "adsense-infeed.njk" %}
{% endif %}
{% endfor %}
adsense-infeed.njk holds the In-feed code AdSense generated for your unit. The not loop.last condition avoids ending the list on an ad.
Verify before you deploy
- Run a production build locally with the flags set (
hugo build, orADS_ENABLED=true npx @11ty/eleventy). - Open the built HTML and confirm the AdSense code appears once, inside
<head>. - Confirm each
<ins>is followed by its push script and that slot IDs are correct. - Confirm
ads.txtis in the output root (public/ads.txtfor Hugo,_site/ads.txtfor Eleventy). - After deploy, load
https://your-domain/ads.txtand check the response is plain text. Hosts that add trailing slashes or rewrites can break it; see ads.txt on static hosts and CDNs.
Common mistakes
- Raw HTML stripped from Markdown. Hugo’s markup configuration sets
renderer.unsafeto false by default, so raw HTML pasted into a content file is not rendered. Use the shortcode instead of turning that setting on. - Head snippet in a partial that only some templates use. Google recommends the AdSense code on every page. Put it in the base template, not in a single-page template.
- Escaped attributes. If you build the script tag from variables, check the final HTML for escaped characters in the
srcURL. A wrong client ID silently prevents ads. - Ads during development. Without a guard, every preview reload sends ad requests you do not want in your reports.
- Hiding units with CSS to “turn them off”. The AdSense code modification policy does not allow hiding ad units with
display:none, apart from responsive units hidden by media query. Remove the shortcode instead.
For approval questions specific to static generators, see AdSense on static and Jamstack sites. To size units per breakpoint, see responsive ad units.
Frequently asked questions
Why does my AdSense shortcode not render in Hugo?
Check three things. The file must be in layouts/_shortcodes (or the shortcodes folder your theme uses), the call should use standard notation {{< adsense slot="1234567890" >}}, and the parameter name must match .Get in the template. With Markdown notation, Hugo processes the shortcode before Markdown rendering, and raw HTML can then be dropped because Goldmark does not render raw HTML by default.
How do I stop AdSense loading during hugo server?
Wrap the partial and the shortcode output in {{ if hugo.IsProduction }}. Hugo's docs say the environment is development when you run hugo server and production otherwise, unless you set --environment or HUGO_ENVIRONMENT. If you deploy previews with a production build, set a separate environment for them.
Can I use the same ad unit shortcode in Eleventy Markdown files?
Yes. Eleventy pre-processes Markdown as Liquid by default, so shortcodes registered with addShortcode work there. Return the HTML as one block with no blank lines inside, because the result then goes through the Markdown parser, and a blank line can end an HTML block early.
Where does ads.txt go in Hugo and Eleventy?
In Hugo, put it in static/ads.txt; the static directory is copied to the output. In Eleventy, add eleventyConfig.addPassthroughCopy("src/ads.txt") if your input folder is src; the input directory is stripped, so it lands at _site/ads.txt and is served at /ads.txt.
Sources
- Shortcode templates · Hugo Documentation
- hugo.Environment · Hugo Documentation
- Directory structure · Hugo Documentation
- Shortcodes · Eleventy Documentation
- Passthrough File Copy · Eleventy Documentation
- Where to place AdSense code in your HTML · Google AdSense Help
Related guides
- Getting a static or Jamstack site approved for AdSense
Getting a static or Jamstack site approved for AdSense: where the code and ads.txt go, why platform subdomains and previews trip reviews, and what stays the same.
- Deploying ads.txt on static hosts and CDNs: public folders, redirects, headers and caching
Where ads.txt goes in Astro, Next.js, Hugo and Eleventy builds, and how Netlify, Vercel, Cloudflare Pages, GitHub Pages and S3 serve, cache and redirect it.
- In-article, In-feed and Multiplex ads: where each native AdSense format belongs and how to place the code
Where AdSense native formats go and how to code them: In-article ads between paragraphs, In-feed ads inside list loops, and Multiplex grids after articles.
- How to add Google AdSense to an Astro site (with or without view transitions)
Add AdSense to an Astro site: unprocessed head script, a reusable ad unit component, ClientRouter view transitions, production-only loading and ads.txt.
- Responsive AdSense ad units: data-ad-format, full-width mobile ads and CSS sizing
How responsive AdSense display units size themselves, what data-ad-format and data-full-width-responsive do, and the CSS media query changes Google allows.