How-to library · Developer docs

How-to library

Task-shaped pages: a title that starts with a verb, the situation in a few lines, the steps, the working code in both engines, and why this way rather than another. Found from a search, done, and left.

Show content only on production

Environment names are free text, so do not test for the word "production". Test that this is the site's primary environment and the request came to one of its own hostnames, once, in the base template.

Context

Context. Analytics, tag managers and search-engine indexing belong on the live site and nowhere else, and a visible "staging" banner belongs everywhere but there. Environment names are typed by hand in the admin, so a test for the word "production" is fragile. The reliable test is structural: is this the site's primary environment, and did the request arrive on one of that environment's own hostnames? A development copy can be someone's primary environment under another hostname, which is why both halves matter.

Steps

  1. Compute the flag once, at the top of the base template.
  2. Store it in the template context so components can read it without recomputing.
  3. Use it for the indexing tag and the analytics snippet, and for a banner on everything else.

Template code

Template code
{$isLive = $_currentSite->isPrimaryEnvironment() && $_currentSite->isHostnameOfCurrentEnvironment($_request->getHostname())}
{$_templateContext->set('isLive', $isLive)}
{if $isLive}
  <script nonce="{$_inlineScriptNonce}" src="/dist/analytics.js?v={$_currentSite->getLastVcsHash()}" defer></script>
{else}
  <meta name="robots" content="noindex, nofollow">
  <div class="env-banner">{$_currentSite->getEnvironmentName()|escape}</div>
{/if}
{% set isLive = _currentSite.isPrimaryEnvironment() and _currentSite.isHostnameOfCurrentEnvironment(_request.getHostname()) %}
{% do _templateContext.set('isLive', isLive) %}
{% if isLive %}
  <script nonce="{{ _inlineScriptNonce }}" src="/dist/analytics.js?v={{ _currentSite.lastVcsHash }}" defer></script>
{% else %}
  <meta name="robots" content="noindex, nofollow">
  <div class="env-banner">{{ _currentSite.getEnvironmentName()|e }}</div>
{% endif %}

Why this and not that

Not the environment name, which is free text and differs between sites. Not the hostname alone, because a site can answer on several and the development copy answers on a rewritten one. Not for features: a feature that should differ between environments belongs in site data, where an editor can switch it without a deploy, and a feature that must never reach production belongs in a branch that never deploys there.

Go deeper

Was this page helpful?

Your answer goes to the docs team.