How do I add meta tags or other content to the page head from a component, with the HTML cache in play?
Question
How do I add meta tags or other content to the page head from a component, with the HTML cache in play?
Answer
Do not write the tag where you stand
A component view is rendered as a fragment and aggregated into the page
later, so markup you emit lands wherever the component sits - in the body. A
<meta> written directly in a component view is not in the head and will not do
what you want.
Use template:addResources instead, which takes body content:
<%@ taglib prefix="template" uri="http://www.jahia.org/tags/templateLib" %>
<template:addResources>
<meta name="description" content="${fn:escapeXml(currentNode.properties['jcr:description'].string)}"/>
</template:addResources>
How it survives the HTML cache
This is the part that makes the question worth asking, and the answer is that you do not have to fight the cache.
template:addResources does not write into the head. It emits a marker
element - jahia:resource - inline, right where your view is. That marker is
ordinary fragment output, so it is stored in the HTML cache along with the rest
of your fragment.
StaticAssetsFilter then runs with applyOnConfigurations = page: it operates on
the assembled page, scanning for jahia:resource markers and relocating their
content into the head. Because that happens on the page render rather than on the
fragment render, it runs on every request - whether your fragment was rendered
fresh or served from cache.
So the contract is: the fragment carries the marker, the page render places it. A cached fragment keeps contributing its head content for as long as it is cached.
What that implies in practice
Cache invalidation is still yours to get right. The mechanism guarantees the marker is relocated, not that its content is current. If your meta tag is derived from a property, and the fragment is cached, the cached marker carries the old value until the fragment is invalidated. The head is as fresh as the fragment that contributed it, no fresher.
Per-user or per-request meta tags do not belong here. A value that varies per visitor, cached in a shared fragment, will leak the first visitor's value to everyone. Either make the fragment per-user cacheable or render that value outside the cached fragment.
Choose the destination if you need to. The tag takes a targetTag attribute
when the head is not where you want it.
Where static tags belong
Meta tags that are the same for every page - or driven by the page itself rather
than by a component - belong in the page template's head, not in a component.
Only reach for addResources when a component needs to contribute something the
template cannot know about.
This article was drafted with AI assistance, then reviewed and curated by Jahia Customer Support engineers before publication.