Functions

Enact provides some functions along side the Twig default functions.

call

Call any native PHP function. This is really powerful, it means you don't need to create a bridge between Twig and PHP to do what PHP lets you by default.

The first argument to call is the function name you want to call, and all arguments after are passed in the exact order you would expect.

{% set content = “<p>Do you 'Carpe Diem'?</p>” %}

{% set replace = '<span class=”quote”>$1</span>' %}


// Lets replace the content in single quotes with a span that has a class

{% set content = call('preg_replace', “'([^']+)'”, replace, content) %}


{{ content }} // <p>Do you <span class=”quote”>Carpe Diem</span>?</p>



// lets shift off the first entry in an array of entries


{% set entries = enact.entry.sectionHandle('blog').order('createdOn DESC').limit(5).fetch %}


{% set firstEntry = call('array_shift', entries) %}



// lets round a number down

{{ call('floor', 34.8) }} // 34



// lets round a number up

{{ call('ceil', 34.8) }} // 35
isActive

Apply a class (by default active) to an entry link when the current page being viewed is that entry. Or return the active class if the current request URI matches the passed URI.

{{ isActive(entry) }} // <a class='active' title='The entry title'>The entry title</a>


<a href='/some-link' class=”{{ isActive('some-link') }}”>View some link</a>


// specify your own class by passing it as the second argument

{{ isActive(entry, 'current') }}
shuffleAssoc

Shuffle an associative array.

{% set items = { 'banna' : 'yellow', 'starfruit' : 'red', 'grape' : 'purple' } %}

{% set items = shuffleAssoc(items) %}
shuffle

Shuffle a numerically indexed array.

{% set items = [ 'yellow',  'red', 'purple' ] %}

{% set items = shuffle(items) %}
random

Get a random element from a numerically indexed array.

{% set entries = enact.entry.sectionHandle('cars') %}

{% set randomCar = random(entries) %}
cacheDuration

Get the number of seconds to cache something for. If you don't pass an argument the default cacheDuration will be returned, if you pass an integer it will be returned. Pass a string to make the real magic happen eg: +1 month, +1 day, +30 minutes, or even 2010-03-20. All these will return the number of seconds until the specified time.

{% set cacheFor = cacheDuration('+1 month') %}
cpSlug

Build a slug pointing to an internal Enact page.

<a href='{{ cpSlug('entry/') }}'>View Entries</a>
cpLink

Build a FQDN link to an internal Enact page.

<a href='{{ cpLink('plugin/') }}'>View Plugins</a>