Global Variables

A number of global variables (opens new window) are available to Twig templates. Some come from Twig itself, and some are Craft-specific.

Global variables are accessible in every Twig template, including system messages and object templates used for element URIs.

This page is split into four sections:

  1. Twig defaults: Variables provided by Twig itself.
  2. Craft: Variables injected by Craft.
  3. Constants: Equivalents of PHP constants.
  4. Elements: Auto-loaded elements.

These lists may be supplemented by plugins, so refer to their documentation to see what kind of functionality is exposed to your templates!

# Twig Defaults

Global variables provided directly by Twig (opens new window).

Variable Description
_self The current template name.
_context The currently-defined variables.
_charset The current charset.

# Craft

Additional variables provided by Craft.

Variable Description
_globals Get and set values on a globally-available store.
craft A craft\web\twig\variables\CraftVariable (opens new window) object.
currentSite The requested site.
currentUser The currently logged-in user.
devMode Whether Dev Mode is enabled.
loginUrl The URL to the front-end Login page.
logoutUrl The URL to the front-end Logout page.
now The current date/time.
setPasswordUrl The URL to the front-end Reset Password (opens new window) page.
siteName The name of the current site.
siteUrl The base URL of the current site.
systemName The system name.
today Midnight of the current day.
tomorrow Midnight, tomorrow.
view The app’s view component.
yesterday Midnight, yesterday.
Global set variables Variables for each of the global sets.
Single variables Variables for each single section entry.

# _globals

An empty Collection object. You may set and get values with the corresponding methods:

{% do _globals.set('theme', 'dark') %}
{% do _globals.set({
  red: '#F00',
  green: '#0F0',
  blue: '#00F',
}) %}

{{ _globals.get('theme') }}
{# -> 'dark' #}

{{ _globals.get('red') }}
{# -> '#F00' #}

The _globals variable has all the native collection methods, as well as a few that Craft provides (via macros (opens new window))—including the set() method used in the example above, which adds support for setting multiple Collection keys at once.

Note that we’re using Twig’s do tag to set values. You can get values in any kind of Twig expression—like an output statement or a set tag.

If you need to set or manipulated nested values, consider creating a top-level Collection object:

{% do _globals.set('events', collect()) %}

{# ... #}

{% do _globals.get('events').push("show:element:#{entry.id}") %}

View the current contents of the _globals variable by passing it to the dump tag:

{# .all() turns the Collection into a plain array: #}
{% dump _globals.all() %}

# craft

A craft\web\twig\variables\CraftVariable (opens new window) object, which provides access points to various helper functions and objects for templates. Many plugins will attach functionality here.

# craft.app

A reference to the main craft\web\Application (opens new window) or craft\console\Application (opens new window) instance (the same object you get when accessing Craft::$app in PHP) is also available to templates via craft.app.

Accessing things via craft.app is considered advanced. There are more security implications than other Twig-specific variables and functions, and your templates will be more susceptible to breaking changes between major Craft versions.

Some of the services commonly used in templates:

Keep in mind that Twig templates can be rendered from web requests, the CLI, and within queue jobs—so there are situations in which certain features may no be available (like the “current user,” or information about the request).

The specific services (or “components”) available via craft.app correspond to the keys defined in Craft’s app.php (opens new window), app.web.php (opens new window), and your project’s equivalent config files.

Here are some examples of these services being used in a template:

{# get the value of an `email` query parameter or post field #}
{% set address = craft.app.request.getParam('email') %}

{# get the value of the `notice` flash message #}
{% set message = craft.app.session.getFlash('notice') %}

{# get the current user’s email address #}
{% set email = craft.app.user.email %}

{# is `devMode` enabled? #}
{% set isDevMode = craft.app.config.general.devMode %}

{# get a custom field by its `body` handle #}
{% set field = craft.app.fields.getFieldByHandle('body') %}

{# get all the sections for the current site #}
{% set sections = craft.app.sections.getAllSections() %}

{# get all the sites for the current Craft installation #}
{% set sites = craft.app.sites.allSites() %}

# currentSite

The requested site, represented by a craft\models\Site (opens new window) object.

{{ currentSite.name }}

You can access all of the sites in the same group as the current site via currentSite.group.sites:

<nav>
  <ul>
    {% for site in currentSite.group.sites %}
      <li><a href="{{ alias(site.baseUrl) }}">{{ site.name }}</a></li>
    {% endfor %}
  </ul>
</nav>

# currentUser

The currently-logged-in user, represented by a craft\elements\User (opens new window) object, or null if no one is logged in.

{% if currentUser %}
  Welcome, {{ currentUser.friendlyName }}!
{% endif %}

# devMode

Whether the devMode config setting is currently enabled.

{% if devMode %}
  Craft is running in dev mode.
{% endif %}

# loginUrl

The URL to your site’s login page, based on the loginPath config setting.

{% if not currentUser %}
  <a href="{{ loginUrl }}">Login</a>
{% endif %}

# logoutUrl

The URL Craft uses to log users out, based on the logoutPath config setting. Note that Craft will automatically redirect users to your homepage after going here; there’s no such thing as a “logout page”.

{% if currentUser %}
  <a href="{{ logoutUrl }}">Logout</a>
{% endif %}

# now

A DateTime (opens new window) object set to the current date and time.

Today is {{ now|date('M j, Y') }}.

# setPasswordUrl

The URL to setPasswordRequestPath if it’s set. (This wraps the path in siteUrl.)

{% if setPasswordUrl %}
  <a href="{{ setPasswordUrl }}">Reset password</a>
{% endif %}

# siteName

The name of the current site, as defined in SettingsSites.

<h1>{{ siteName }}</h1>

# siteUrl

The base URL of the current site.

<link rel="home" href="{{ siteUrl }}">

To generate a URL relative to the current site, use the siteUrl() function.

# systemName

The System Name, as defined in SettingsGeneral.

# today

A DateTime (opens new window) object in the system’s timezone, set to midnight (00:00 in 24-hour time, or 12:00AM in 12-hour) of the current day.

# tomorrow

A DateTime (opens new window) object in the system’s timezone, set to midnight (00:00 in 24-hour time, or 12:00AM in 12-hour) of the next day.

# view

A reference to the craft\web\View (opens new window) instance that is driving the template.

# yesterday

A DateTime (opens new window) object in the system’s timezone, set to midnight (00:00 in 24-hour time, or 12:00AM in 12-hour) of the previous day.

# PHP Constants + Equivalents

Twig doesn’t distinguish between variables and constants, nor does it expose PHP’s global constants for use in templates (except via the constant() function, discussed below). However, Craft exposes a few that make it easier to work with built-in features.

Variable Description
POS_BEGIN The craft\web\View::POS_BEGIN (opens new window) constant.
POS_END The craft\web\View::POS_END (opens new window) constant.
POS_HEAD The craft\web\View::POS_HEAD (opens new window) constant.
POS_LOAD The craft\web\View::POS_LOAD (opens new window) constant.
POS_READY The craft\web\View::POS_READY (opens new window) constant.
SORT_ASC The SORT_ASC PHP constant.
SORT_DESC The SORT_DESC PHP constant.
SORT_FLAG_CASE The SORT_FLAG_CASE PHP constant.
SORT_LOCALE_STRING The SORT_LOCALE_STRING PHP constant.
SORT_NATURAL The SORT_NATURAL PHP constant.
SORT_NUMERIC The SORT_NUMERIC PHP constant.
SORT_REGULAR The SORT_REGULAR PHP constant.
SORT_STRING The SORT_STRING PHP constant.

Other constants are accessible with the constant() function (opens new window). Pass a string representing the way you would access it in PHP, including (when applicable) the fully-qualified, properly-escaped class name:

{# You can fetch native PHP constants... #}
{{ constant('PHP_VERSION') }}

{# ...constants defined by Craft... #}
{{ constant('CRAFT_BASE_PATH') }}

{# ...and even class constants: #}
{{ constant('craft\\elements\\Entry::STATUS_LIVE') }}

# POS_BEGIN

Twig-facing copy of the craft\web\View::POS_BEGIN (opens new window) constant. Used in conjunction with the registration of JS and HTML fragments to place them at the beginning of the <body> element in the rendered page:

{% set js %}
  console.log('Hello, Craft!');
{% endset %}

{% do view.registerJs(js, POS_BEGIN) %}

# POS_END

Twig-facing copy of the craft\web\View::POS_END (opens new window) constant. Used in conjunction with the registration of JS and HTML fragments to place them at the end of the <body> element in the rendered page:

{% set js %}
  console.log('Goodbye, Craft!');
{% endset %}

{% do view.registerJs(js, POS_END) %}

# POS_HEAD

Twig-facing copy of the craft\web\View::POS_HEAD (opens new window) constant. Used in conjunction with the registration of JS and HTML fragments to place them at the end of the <head> element in the rendered page:

{% set js %}
  console.log('Where am I?!');
{% endset %}

{% do view.registerJs(js, POS_HEAD) %}

# POS_LOAD

Twig-facing copy of the craft\web\View::POS_LOAD (opens new window) constant. Used only for registering JS fragments, wrapping the code in a jQuery “load” handler:

{% set js %}
  console.log('Page has finished loading.');
{% endset %}

{% do view.registerJs(js, POS_LOAD) %}

Using POS_LOAD with view.registerJs() causes Craft to include its own copy of jQuery in the page.

# POS_READY

Twig-facing copy of the craft\web\View::POS_READY (opens new window) constant. Used in the same way as POS_LOAD, but passes the script body to jQuery’s ready (opens new window) handler:

jQuery(function ($) {
  console.log('DOM is ready.');
});

# SORT_ASC

Twig-facing copy of the SORT_ASC PHP constant.

# SORT_DESC

Twig-facing copy of the SORT_DESC PHP constant.

# SORT_FLAG_CASE

Twig-facing copy of the SORT_FLAG_CASE PHP constant.

# SORT_LOCALE_STRING

Twig-facing copy of the SORT_LOCALE_STRING PHP constant.

# SORT_NATURAL

Twig-facing copy of the SORT_NATURAL PHP constant.

# SORT_NUMERIC

Twig-facing copy of the SORT_NUMERIC PHP constant.

# SORT_REGULAR

Twig-facing copy of the SORT_REGULAR PHP constant.

# SORT_STRING

Twig-facing copy of the SORT_STRING PHP constant.

# Automatically Loaded Elements

Craft makes some elements available to all templates.

# Global Sets

Each of your site’s global sets will be available to your templates as global variables, named the same as their handle.

They will be represented as craft\elements\GlobalSet (opens new window) objects.

<p>{{ companyInfo.companyName }} was established in {{ companyInfo.yearEstablished }}.</p>

# Singles

Your single section entries can also be loaded automatically by setting preloadSingles to true.

# Other Elements

When an element’s URI is requested, Craft automatically loads that element into the Twig environment before rendering the template defined in the element type’s settings.

For entries, the variable is always named entry; for categories, category. Element types provided by plugins may obey other conventions!