Dot All Lisbon – the official Craft CMS conference – is happening September 23 - 25.
Global Variables
A number of global variables 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:
- Twig defaults: Variables provided by Twig itself.
- Craft: Variables injected by Craft.
- Constants: Equivalents of PHP constants.
- 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.
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 craft5:craft\web\twig\variables\CraftVariable 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.
primarySite <Since ver="5.6.0" feature="Global Twig variable for the primary site" /> | In multi-site projects, the “primary” site.
setPasswordUrl | The URL to the front-end Reset Password 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)—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 craft5:craft\web\twig\variables\CraftVariable 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 craft5:craft\web\Application or craft5:craft\console\Application 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:
craft.app.request
– Request object with information about the current HTTP requestcraft.app.session
– Session object useful for getting and setting flash messagescraft.app.user
– User object for getting information about the client’s identitycraft.app.config.general
– GeneralConfig object of General Config Settingscraft.app.fields
– Fields service for accessing custom field detailscraft.app.sites
– Sites service for getting site details
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
, app.web.php
, 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.entries.getAllSections() %}
{# get all the sites for the current Craft installation #}
{% set sites = craft.app.sites.allSites() %}
currentSite
The requested site, represented by a craft5:craft\models\Site object.
{{ currentSite.name }}
You can access all of the sites in the same group as the current site via currentSite.group.sites
:
<ul>
{% for site in currentSite.group.sites %}
<li><a href="{{ alias(site.baseUrl) }}">{{ site.name }}</a></li>
{% endfor %}
</ul>
currentUser
The currently-logged-in user, represented by a craft5:craft\elements\User object, or null
if no one is logged in.
{% if currentUser %}
Welcome, {{ currentUser.friendlyName }}!
{% endif %}
Some templates are rendered in contexts that don’t use sessions or have any concept of a “current user,” like the command line. System messages are also somewhat unintuitive in this regard, because the current user may not be the recipient!
devMode
Whether the config5: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 config5:loginPath config setting.
{% if not currentUser %}
<a href="{{ loginUrl }}">Login</a>
{% endif %}
logoutUrl
The URL Craft uses to log users out, based on the config5: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 object set to the current date and time.
Today is {{ now|date('M j, Y') }}.
primarySite
<Since ver="5.6.0" feature="Global Twig variable for the primary site" />
The primary site (as designated in <Journey path="Settings, Sites" />), as an instance of craft4:craft\models\Site.
{# Output the primary site’s name: #}
We are a proud member of {{ primarySite.name }}
{# Link to a page on the primary site: #}
{{ tag('a', {
href: siteUrl('about/governance', siteId = primarySite.id),
text: 'Learn about our family of businesses',
}) }}
primarySite
will be a reference to the same object as currentSite
, when currentSite.primary
is true
. You can also retrieve the primary site via craft.app.sites.primarySite
.
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 Settings → Sites.
siteUrl
The base URL of the current site.
To generate a URL relative to the current site, use the siteUrl()
function.
systemName
The System Name, as defined in Settings → General.
today
A DateTime 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 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 craft5:craft\web\View instance that is driving the template.
yesterday
A DateTime 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 constant.
POS_END | The craft\web\View::POS_END constant.
POS_HEAD | The craft\web\View::POS_HEAD constant.
POS_LOAD | The craft\web\View::POS_LOAD constant.
POS_READY | The craft\web\View::POS_READY 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. 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 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 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 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 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) %}
jQuery(window).on('load', function () {
console.log('Page has finished loading.');
});
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 constant. Used in the same way as POS_LOAD
, but passes the script body to jQuery’s ready 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 craft5:craft\elements\GlobalSet objects.
Singles
Your single section entries can also be loaded automatically by setting config5:preloadSingles to true
. This makes them available by handle in all Twig contexts, just as global sets are. For example, if you had an “About Us” single with the handle about
, you could access content from that entry in your footer, without setting up a query:
©{{ now|date('Y') }}
{{ about.phoneNumber }}
When you convert a global set to a single using the [`entrify/global-set` command](../cli.md#entrify-global-set), template references should remain compatible, so long as <config5:preloadSingles> is enabled.
### 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](../../system/elements.md)’s settings.
For [entries](../element-types/entries.md), the variable is always named `entry`; for [categories](../element-types/categories.md), `category`. Element types provided by plugins may obey other conventions!