Functions

The following functions are available to Twig templates in Craft:

actionInput

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'
}) }}

alias

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') }}">

attr

Generates a list of HTML attributes based on the given object, using 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>

attribute

Accesses a dynamic attribute of a variable.

This works identically to Twig’s core attribute function.

beginBody

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>

block

Prints a block’s output.

This works identically to Twig’s core block function.

ceil

Rounds a number up.

{{ ceil(42.1) }}
{# Output: 43 #}

className

Returns the fully qualified class name of a given object.

{% set class = className(entry) %}
{# Result: 'craft\\elements\\Entry' #}

clone

Clones a given object.

{% set query = craft.entries.section('news') %}
{% set articles = clone(query).type('articles') %}

constant

Returns the constant value for a given string.

This works identically to Twig’s core constant function.

create

Creates a new object instance based on a given class name or object configuration. See 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'
}) %}

csrfInput

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'
}) }}

cycle

Cycles on an array of values.

This works identically to Twig’s core cycle function.

date

Converts an argument to a date.

This works identically to Twig’s core date function.

dump

Dumps information about a template variable.

This works identically to Twig’s core dump function.

endBody

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>

expression

Creates and returns a new yii\db\Expression object, for use in database queries.

{% set entries = craft.entries()
    .andWhere(expression('[[authorId]] = :authorId', {authorId: currentUser.id}))
    .all() %}

floor

Rounds a number down.

{{ floor(42.9) }}
{# Output: 42 #}

getenv

Returns the value of an environment variable.

{{ getenv('MAPS_API_KEY') }}

gql

Executes a GraphQL query against the full schema.

{% set result = gql('{
  entries (section: "news", limit: 2, orderBy: "dateCreated DESC") {
    postDate @formatDateTime (format: "Y-m-d")
    title
    url
    ... on news_article_Entry {
      shortDescription
      featuredImage {
        url @transform (width: 300, immediately: true)
        altText
      }
    }
  }
}') %}

{% for entry in result.data. %}
    <h3><a href="{{ entry.url }}">{{ entry.title }}</a></h3>
    <p class="timestamp">{{ entry.postDate }}</p>

    {% set image = entry.featuredImage[0] %}
    <img class="thumb" src="{{ image.url }}" alt="{{ image.altText }}">

    {{ entry.shortDescription|markdown }}
    <p><a href="{{ entry.url }}">Continue reading…</a></p>
{% endfor %}

parseEnv

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'
}) }}

include

Returns the rendered content of a template.

This works identically to Twig’s core include function.

input

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'
}) }}

max

Returns the biggest value in an array.

This works identically to Twig’s core max function.

min

Returns the lowest value in an array.

This works identically to Twig’s core min function.

parent

Returns the parent block’s output.

This works identically to Twig’s core parent function.

plugin

Returns a plugin instance by its handle, or null if no plugin is installed and enabled with that handle.

{{ plugin('commerce').version }}

random

Returns a random value.

This works identically to Twig’s core random function.

range

Returns a list containing an arithmetic progression of integers.

This works identically to Twig’s core range function.

redirectInput

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'
}) }}

seq

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>

shuffle

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 %}

siteUrl

Similar to url(), except only for creating URLs to pages on your site.

<a href="{{ siteUrl('company/contact') }}">Contact Us</a>

Arguments

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, then https will be used.
  • siteId – The ID of the site that the URL should point to. By default the current site will be used.

svg

Outputs an SVG document.

You can pass the following things into it:

  • An SVG file path.

    {{ svg('@webroot/icons/lemon.svg') }}
    
  • A 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') }}

source

Returns the content of a template without rendering it.

This works identically to Twig’s core source function.

tag

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 yii\helpers\BaseHtml::renderTagAttributes().

template_from_string

Loads a template from a string.

This works identically to Twig’s core template_from_string function.

url

Returns a URL.

<a href="{{ url('company/contact') }}">Contact Us</a>

Arguments

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, then https will be used.
  • mustShowScriptName – If this is set to true, then the URL returned will include “index.php”, disregarding the 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" #}