Sub topic 15
Generating tags in templates and frameworks
This chapter assumes you know the HTML head, URL query strings, and how titles, descriptions, and canonicals work. Here you will generate those tags from one place in your code, so every page gets them without hand-editing.
Why generate tags
Hand-written tags drift. A copied page keeps the old title, a new page ships with no description, and a canonical points to a staging host. A template fixes this by building the head from page data. Each page supplies a few fields, and the layout turns them into tags.
The layout should do three jobs:
- Build the title from page data, with a fallback when the field is empty.
- Output the description only when you have real text for it.
- Compute one absolute canonical URL for every request.
A single head builder
Put the logic in one function that every page template calls. The example below uses plain JavaScript, so it runs in Node.js without a framework.
const SITE_URL = "https://www.example.com";
const SITE_NAME = "Example Store";
const TRACKING_PARAMS = new Set(["gclid", "fbclid"]);
function escapeHtml(text) {
return String(text)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function canonicalUrl(path) {
const url = new URL(path, SITE_URL);
url.hash = "";
for (const key of [...url.searchParams.keys()]) {
if (key.startsWith("utm_") || TRACKING_PARAMS.has(key)) {
url.searchParams.delete(key);
}
}
return url.toString();
}
function renderHead(page, requestPath) {
const title = page.title
? `${page.title} | ${SITE_NAME}`
: SITE_NAME;
const lines = [
'<meta charset="utf-8">',
`<title>${escapeHtml(title)}</title>`,
];
if (page.description) {
lines.push(
`<meta name="description" content="${escapeHtml(page.description)}">`
);
}
lines.push(
`<link rel="canonical" href="${escapeHtml(canonicalUrl(requestPath))}">`
);
return lines.join("\n");
}
console.log(
renderHead(
{
title: "Trail Running Shoes for Beginners",
description: "Compare cushioned trail running shoes for first-time runners.",
},
"/shoes/trail-running?utm_source=newsletter"
)
);The function uses the site's own base URL, not the request's Host header. That keeps the canonical on your chosen host even if the page is reached through another hostname. The escapeHtml call matters because titles often contain & or quotes, which would otherwise break the attribute.
How the pieces fit
The page data flows through the layout once per request.
Framework equivalents
Most frameworks provide a hook for this, so you rarely write the string yourself. The names differ, but the pattern is the same: declare the values per page and let the layout render them.
| Stack | Where you set tags |
|---|---|
| Next.js (App Router) | `metadata` export or `generateMetadata`, with `alternates.canonical` |
| Nuxt | `useHead` or `useSeoMeta` |
| Django or Jinja templates | A `{% block head %}` in the base template |
| Static site generators | Front matter fields read by the base layout |
Whichever you use, check the rendered HTML, not the template. Client-side rendering can leave tags unset until JavaScript runs, and crawlers may read the raw response first. Prefer server-side or build-time rendering for these three tags.
Common errors
- Pages with no title field render an empty or generic title. Use a fallback and flag the page in your audit.
- Relative canonical paths are easy to produce by mistake. Always resolve against the site URL.
- Descriptions copied from a template default make every page identical. Omit the tag instead.
- Pagination or filter pages inherit the canonical of the first page. Compute it from the request, then decide deliberately which variants should point elsewhere.
Exercise
A product page template builds its canonical from the incoming request's Host header. Staging traffic reaches the page at https://staging.example.com/shoes. What goes wrong, and what is the fix?
Show answer
The canonical becomes https://staging.example.com/shoes, so the staging host can be indexed as the preferred version. Fix it by resolving the path against a fixed production site URL, as the SITE_URL constant does in the head builder.