The following functions are available to Twig templates in Craft:
A shortcut for outputting a hidden input used to route a POST request to a particular controller action. This is effectively the same as writing <input type="hidden" name="action" value="controller/action/route">
directly into a template.
{{ actionInput('users/save-user') }}
You can optionally set additional attributes on the tag by passing an options
argument.
{{ actionInput('users/save-user', {
id: 'action-input'
}) }}
Passes a string through Craft::getAlias(), which will check if the string begins with an alias. (See Configuration for more info.)
<img src="{{ alias('@assetBaseUrl/images/logo.png') }}">
Generates a list of HTML attributes based on the given object, using api:yii\helpers\BaseHtml::renderTagAttributes().
{% set myAttributes = {
class: ['one', 'two'],
disabled: true,
readonly: false,
data: {
baz: 'Escape this "',
qux: {
some: ['data', '"quoted"']
}
},
style: {
'background-color': 'red',
'font-size': '20px'
},
} %}
<div {{ attr(myAttributes) }}></div>
Accesses a dynamic attribute of a variable.
This works identically to Twig’s core attribute
function.
Outputs any scripts and styles that were registered for the “begin body” position. It should be placed right after your <body>
tag.
<body>
{{ beginBody() }}
<h1>{{ page.name }}</h1>
{{ page.body }}
</body>
Prints a block’s output.
This works identically to Twig’s core block
function.
Rounds a number up.
{{ ceil(42.1) }}
{# Output: 43 #}
Returns the fully qualified class name of a given object.
{% set class = className(entry) %}
{# Result: 'craft\\elements\\Entry' #}
Clones a given object.
{% set query = craft.entries.section('news') %}
{% set articles = clone(query).type('articles') %}
Returns the constant value for a given string.
This works identically to Twig’s core constant
function.
Creates a new object instance based on a given class name or object configuration. See api:Yii::createObject() for a full explanation of supported arguments.
{# Pass in a class name #}
{% set cookie = create('yii\\web\\Cookie') %}
{# Or a full object configuration array #}
{% set cookie = create({
class: 'yii\\web\\cookie',
name: 'foo',
value: 'bar'
}) %}
Returns a hidden CSRF Token input. All sites that have CSRF Protection enabled must include this in each form that submits via POST.
{{ csrfInput() }}
You can optionally set additional attributes on the tag by passing an options
argument.
{{ csrfInput({
id: 'csrf-input'
}) }}
Cycles on an array of values.
This works identically to Twig’s core cycle
function.
Converts an argument to a date.
This works identically to Twig’s core date
function.
Dumps information about a template variable.
This works identically to Twig’s core dump
function.
Outputs any scripts and styles that were registered for the “end body” position. It should be placed right before your </body>
tag.
<body>
<h1>{{ page.name }}</h1>
{{ page.body }}
{{ endBody() }}
</body>
Creates and returns a new api:yii\db\Expression object, for use in database queries.
{% set entries = craft.entries()
.andWhere(expression('[[authorId]] = :authorId', {authorId: currentUser.id}))
.all() %}
Rounds a number down.
{{ floor(42.9) }}
{# Output: 42 #}
Returns the value of an environment variable.
{{ getenv('MAPS_API_KEY') }}
Checks if a string references an environment variable ($VARIABLE_NAME
) and/or an alias (@aliasName
), and returns the referenced value.
Outputs any scripts and styles that were registered for the “head” position. It should be placed right before your </head>
tag.
<head>
<title>{{ siteName }}</title>
{{ head() }}
</head>
hiddenInput
Generates an HTML input tag.
{{ hiddenInput('entryId', entry.id) }}
{# Output: <input type="hidden" name="entryId" value="100"> #}
You can optionally set additional attributes on the tag by passing an options
argument.
{{ hiddenInput('entryId', entry.id, {
id: 'entry-id-input'
}) }}
Returns the rendered content of a template.
This works identically to Twig’s core include
function.
Generates an HTML input tag.
{{ input('email', 'email-input', '') }}
{# Output: <input type="email" name="email-input" value=""> #}
You can optionally set additional attributes on the tag by passing an options
argument.
{{ input('email', 'email-input', '', {
id: 'custom-input'
}) }}
Returns the biggest value in an array.
This works identically to Twig’s core max
function.
Returns the lowest value in an array.
This works identically to Twig’s core min
function.
Returns the parent block’s output.
This works identically to Twig’s core parent
function.
Returns a plugin instance by its handle, or null
if no plugin is installed and enabled with that handle.
{{ plugin('commerce').version }}
Returns a random value.
This works identically to Twig’s core random
function.
Returns a list containing an arithmetic progression of integers.
This works identically to Twig’s core range
function.
Shortcut for typing <input type="hidden" name="redirect" value="{{ url|hash }}">
.
{{ redirectInput(url) }}
You can optionally set additional attributes on the tag by passing an options
argument.
{{ redirectInput(url, {
id: 'redirect-input'
}) }}
Outputs the next or current number in a sequence, defined by name
:
<p>This entry has been read {{ seq('hits:' ~ entry.id) }} times.</p>
Each time the function is called, the given sequence will be automatically incremented.
You can optionally have the number be zero-padded to a certain length.
{{ now|date('Y') ~ '-' ~ seq('orderNumber:' ~ now|date('Y'), 5) }}
{# outputs: 2018-00001 #}
To view the current number in the sequence without incrementing it, set the next
argument to false
.
<h5><a href="{{ entry.url }}">{{ entry.title }}</a></h5>
<p>{{ seq('hits:' ~ entry.id, next=false) }} views</p>
Randomizes the order of the elements within an array.
{% set promos = shuffle(homepage.promos) %}
{% for promo in promos %}
<div class="promo {{ promo.slug }}">
<h3>{{ promo.title }}</h3>
<p>{{ promo.description }}</p>
<a class="cta" href="{{ promo.ctaUrl }}">{{ promo.ctaLabel }}</a>
</div>
{% endfor %}
Similar to url(), except only for creating URLs to pages on your site.
<a href="{{ siteUrl('company/contact') }}">Contact Us</a>
The siteUrl()
function has the following arguments:
path
– The path that the resulting URL should point to on your site. It will be appended to your base site URL.params
– Any query string parameters that should be appended to the URL. This can be either a string (e.g.'foo=1&bar=2'
) or an object (e.g.{foo:'1', bar:'2'}
).scheme
– Which scheme the URL should use ('http'
or'https'
). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, thenhttps
will be used.siteId
– The ID of the site that the URL should point to. By default the current site will be used.
Outputs an SVG document.
You can pass the following things into it:
-
An SVG file path.
{{ svg('@webroot/icons/lemon.svg') }}
-
A api:craft\elements\Asset object, such as one pulled in from an Assets field.
{% set image = entry.myAssetsField.one() %} {% if image and image.extension == 'svg' %} {{ svg(image) }} {% endif %}
-
Raw SVG markup.
{% set image = include('_includes/icons/lemon.svg') %} {{ svg(image) }}
By default, if you pass an asset or raw markup into the function, the SVG will be sanitized of potentially malicious scripts using svg-sanitizer, and any IDs or class names within the document will be namespaced so they don’t conflict with other IDs or class names in the DOM. You can disable those behaviors using the sanitize
and namespace
arguments:
{{ svg(image, sanitize=false, namespace=false) }}
You can also specify a custom class name that should be added to the root <svg>
node using the class
argument:
{{ svg('@webroot/icons/lemon.svg', class='lemon-icon') }}
Returns the content of a template without rendering it.
This works identically to Twig’s core source
function.
Renders a complete HTML tag.
{{ tag('div', {
class: 'foo'
}) }}
{# Output: <div class="foo"></div> #}
If text
is included in the attributes argument, its value will be HTML-encoded and set as the text contents of the tag.
{{ tag('div', {
text: 'Hello'
}) }}
{# Output: <div>Hello</div> #}
If html
is included in the attributes argument (and text
isn’t), its value will be set as the inner HTML of the tag (without getting HTML-encoded).
{{ tag('div', {
html: 'Hello<br>world'
}) }}
{# Output: <div>Hello<br>world</div> #}
All other keys passed to the second argument will be set as attributes on the tag, using api:yii\helpers\BaseHtml::renderTagAttributes().
Loads a template from a string.
This works identically to Twig’s core template_from_string
function.
Returns a URL.
<a href="{{ url('company/contact') }}">Contact Us</a>
The url()
function has the following arguments:
path
– The path that the resulting URL should point to on your site. It will be appended to your base site URL.params
– Any query string parameters that should be appended to the URL. This can be either a string (e.g.'foo=1&bar=2'
) or an object (e.g.{foo:'1', bar:'2'}
).scheme
– Which scheme the URL should use ('http'
or'https'
). The default value depends on whether the current request is served over SSL or not. If not, then the scheme in your Site URL will be used; if so, thenhttps
will be used.mustShowScriptName
– If this is set totrue
, then the URL returned will include “index.php”, disregarding the config:omitScriptNameInUrls config setting. (This can be useful if the URL will be used by POST requests over Ajax, where the URL will not be shown in the browser’s address bar, and you want to avoid a possible collision with your site’s .htaccess file redirect.)
::: tip
You can use the url()
function for appending query string parameters and/or enforcing a scheme on an absolute URL:
{{ url('http://my-project.com', 'foo=1', 'https') }}
{# Outputs: "https://my-project.com?foo=1" #}
:::