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 <Since ver="4.5.0" feature="The _globals Twig variable" /> | Get and set values on a globally-available store.
craft | A craft4: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="4.14.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. <Since ver="4.4.0" feature="Global variables for single entries" />
_globals
<Since ver="4.5.0" feature="The _globals Twig variable" />
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 craft4: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 craft4:craft\web\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 representing the logged-in human (when applicable)craft.app.config.general
– GeneralConfig object of General Config Settingscraft.app.fields
– Fields service for accessing custom field detailscraft.app.sections
– Sections service for working with sections and entry typescraft.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.sections.getAllSections() %}
{# get all the sites for the current Craft installation #}
{% set sites = craft.app.sites.allSites() %}
currentSite
The requested site, represented by a craft4: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 craft4:craft\elements\User object, or null
if no one is logged in.
{% if currentUser %}
Welcome, {{ currentUser.friendlyName }}!
{% endif %}
devMode
Whether the config4: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 config4:loginPath config setting.
{% if not currentUser %}
<a href="{{ loginUrl }}">Login</a>
{% endif %}
logoutUrl
The URL Craft uses to log users out, based on the config4: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="4.14.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
<Since ver="4.3.0" feature="The today global variable" />
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
<Since ver="4.3.0" feature="The tomorrow global variable" />
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 craft4:craft\web\View instance that is driving the template.
yesterday
<Since ver="4.3.0" feature="The yesterday global variable" />
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 craft4:craft\elements\GlobalSet objects.
Singles <Since ver="4.4.0" feature="auto-loaded singles" />
Your single section entries can also be loaded automatically by setting config4: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!