Filters

Filters in Twig allow you to modify a variable's data before you use it. The most common use is to apply the filter when you are outputting the content. For example:

{{ post.postTitle|title }}

You can also apply filters when you assign a variable's value to another variable. Below is a simple example:

{% set firstCategory = post.categories|first %}

Just about anywhere you work with variables you can apply a filter.

Chaining filters

You can also chain filters to perform a number of alterations at once.

{{ variable|truncate(20)|title }}

Named arguments

With all filters that accept one or more optional arguments, you can use named arguments. This allows you to only pass the arguments that you need to.

For example, the date filter supports two arguments, format and timezone. Both are optional. if you only wanted to pass the timezone argument there are two choices.

You could pass null as the the format argument to allow the default value to be used.

{{ "now"|date(null, 'Europe/Paris') }}

Or, you could use the name of the argument to pass only the timezone argument.

{{ "now"|date(timezone='Europe/Paris') }}

You can also use named arguments to make your code more clear.

{% for post in posts|slice(start=3, length=6) %}
{% endfor %}

You can also use both positional and named arguments in one call. If this is done then positional arguments must always come before named arguments.

{{ "now"|date('d/m/Y H:i', timezone='Europe/Paris') }}

List of available filters

abs

Returns an absolute value for a number.

{{ number|abs }}

Learn more about the abs filter

batch

The batch filter breaks up an array into groups of arrays with the given number of items.

{% for row in items|batch(3, 'No item') %}
{% endfor %}

camel

Takes a series of words and camel cases them.

{{ variable|camel }}

Learn more about the camel filter

capitalize

Changes the first letter of the value to be uppercase. All other characters will be lower case.

{{ variable|capitalize }}

ceiling

Rounds up a number.

{{ number|ceiling }}

country_abbreviation

Gets the 2 letter country abbreviation for the variable value if the variable value is a valid country or country abbreviation.

{{ variable|country_abbreviation }}

country_data

Gets an array of country data for the variable value if the variable value is a valid country or country abbreviation.

The array contains the following information:
abbreviation: the 2 letter country abbreviation
name
: the full country name

{% set data = variable|country_data %}

country_name

Gets the full country name for the variable value if the variable value is a valid country or country abbreviation.

{{ variable|country_name }}

date

Formats a date to a given format.

{{ post.publishedOnTimestamp|date('M d, Y') }}

Learn more about the date filter

date_modify

Modifies a date based on the passed modifier.

{{ post.publishedOnTimestamp|date_modify('+ 1 day')|date('m/d/Y') }}

debug

Outputs the results of a variable in a debug statmenet. Useful for development.

{{ post|debug }}

{{ form.fields('Form fields') }}

default

Returns the passed default value if the variable is undefined or empty, otherwise, it returns the variable value.

{{ variable|default('My Default Value') }}

Learn more about the default filter

embed_media

Takes a string and looks for any URLs for embeddable resources (YouTube videos for example) and using the oEmbed protocol converts the URL into the appropriate embed code.

{{ variable|embed_media }}

escape

Escapes a string for final output. Useful for user-entered data where you're not sure that the data is safe.

{{ variable|escape }}

escape_quotes

Escapes single and double quotes with a backslash "\". By default it will escape both double and single quotes but you can specify which one you want to escape.

{{ variable|escape_quotes }}

{{ variable|escape_quotes('single') }}

{{ variable|escape_quotes('double') }}

file_url

Prepends the CDN or S3 URL of the file to the file path. 

<link rel="icon" type="image/png" href="{{ 'favicon.ico'|file_url }}">

Learn more about the file_url filter

first

Returns the first value of an array, hash or string.

{{ [1, 2, 3, 4]|first }}

Learn more about the first filter

float

Converts the value to a float number.

{{ variable|float }}

floor

Rounds a number down. You can also specify a precision.

{{ number|floor }}

{{ number|floor(2) }}

format

Formats a string by replacing the placeholders with the specified values.

{{ 'I like %s and %s'|format('icecream', 'pickles') }}

html2text

Converts an HTML string to plain text.

{{ htmlVariable|html2text }}

html_entities

Converts HTML entities to their entity value.

{{ '<p><b>All</b> HTMl code will be converted</p>'|html_entities }}

html_special_characters

Converts only special characters to their HTML entity. (& " ' < >)

{{ 'Only &, <, >, " and \' will be converted'|html_special_chars }}

inject_html

Inserts an HTML snippet immediately before a closing block level tag (</p> </div>) or a closing span tag </span> if they are the last HTML tag in the variable value. If they are not then the HTML snippet is simply appended to the variable value.

{{ post.abstract|inject_html(' <a href="' ~ post.url ~ '">Read more<a>') }}

integer

Converts the value to an integer.

{{ variable|integer }}

join

Concatenates the values of an array into a string, optionally separated by the passed separator.

{{ array|join(' | ') }}

Learn more about the join filter

json

Encodes the value as a complete JSON string.

{{ {'fruit': 'apple', 'vegetable': 'lettuce'}|json }}

Learn more about the json filter

json_decode

Converts a JSON string into an array of values.

{% set data = jsonString|json_decode %}

json_encode

Returns the JSON representation of a value.

{{ post.postTitle|json_encode }}

kebab

Takes a string and creates a lowercase version of it with words separated by dashes instead of spaces. Useful for creating anchor links.

{{ "Bob Smith"|kebab }}

Learn more about the kebab filter

keys

Returns the keys of an array.

{% for key in array|keys %}
{% endfor %}

Learn more about the keys filter

krsort

Sorts an array or hash by its keys in reverse order (Z-A).

{% set array = array|krsort %}

Learn more about the krsort filter

ksort

Sorts an array or hash by its keys.

{% set array = array|ksort %}

Learn more about the ksort filter

last

Returns the last element of an array, hash or string.

{{ [1, 2, 3, 4]|last }}

lcfirst

Lowercases the first letter of a string

{{ variable|lcfirst }}

Learn more about the lcfirst filter

length

Returns the number of items in an array or hash, or the length of a string.

{{ post.postTitle|length }}

Learn more about the length filter

lower

Converts the string value to all lower case.

{{ 'I SHOULD BE LOWERCASE'|lower }}

ltrim

Trims the begining of a string for whitespace or a specific character.

{{ string|ltrim }}

md5

Converts the string to an MD5 hash.

{% set hash = post.postTitle|md5 %}

md5_hmac

Converts the string to an MD5 hash using the HMAC method.

{% set hash = post.postTitle|md5_hmac('secret_key') %}

merge

Merges an array with another array.

{% set data = ['apple', 'bannana', 'orange']|merge(['grapes', 'pinapple']) %}

nl2array

Splits a string on new line characters and returns an array of the string parts.

{% set data = var|nl2array %}

nl2br

Converts new line characters in a string to <br> tags.

{{ string|nl2br }}

nlc2array

Splits a string on new line characters or commas an returns an array of the string parts.

{% set data = var|nlc2array %}

number_format

Formats a number to have a certain number of decimal points, a specific decimal point character, and thousands separator.

{{ 3024.2|number_format(2) }}

pascal

Takes a series of words and PascalCases them.

{{ variable|pascal }}

Learn more about the pascal filter

raw

Marks a value as "safe" meaning it won't be auto escaped.

{% autoescape %}
    {{ var|raw }}
{% endautoescape %}

regex_filter

Replaces values within a string by a regular expression and returns only the (possibly transformed) subjects where there was a match.

{% set new = ['x', 'y', 'z', 'm', 'e', '3', '10']|regex_filter(['/\\d/', '/[x-z]/'], ['$0 is a NUMBER ', '$0 is a LETTER ']) %}

Learn more about the regex_filter filter

regex_grep

Searches an array for values that match the regular expression and returns an array of the matches.

{% set results = [123, 0.456, "xyz", '3.5']|regex_grep('/^(\\d+)?\\.\\d+$/') %}

Learn more about the regex_grep filter

regex_grep_invert

Searches an array for values that match the regular expression and returns an array of values that do not match the regular expression.

{% set results = [123, 0.456, "xyz", '3.5']|regex_grep('/^(\\d+)?\\.\\d+$/') %}

Learn more about the regex_grep_invert filter

regex_match

Searches the value for the first match to the regular expression and returns the result.

{{ 'Sam likes <b>hotdogs</b> and relish'|regex_match('/<b>(.*?)<\\/b>/') }}
{{ 'Sam likes <b>hotdogs</b> and relish'|regex_match('/<b>(.*?)<\\/b>/', 1) }}
{{ 'abcdefg'|regex_match('/(ab)(cd)(efg)/', 2) }}

Learn more about the regex_match filter

regex_match_all

Searches the value for all matches to the regular expression and returns the results as an array.

{% set matches = 'Sam likes <b>hotdogs</b> and <b>relish</b>'|regex_match_all('/<b>(.*?)<\\/b>/') %}
{% set matches = 'Sam likes <b>hotdogs</b> and <b>relish</b>'|regex_match_all('/<b>(.*?)<\\/b>/', 1) %}

Learn more about the regex_match_all filter

regex_quote

Quotes regular expression characters.

{{ value|regex_quote() }}
{{ value|regex_quote('#') }}

Learn more about the regex_quote filter

regex_replace

Replaces values within a string, or an array of strings, by a regular expression or an array of regular expressions.

{{ 'Make me a kebab string'|lower|regex_replace('/[^\\w]+/', '-') }}

Learn more about the regex_replace filter

regex_split

Splits the string value by a regular expression.

{% set parts = 'Separate this sentence by spaces, commas, and more spaces.'|regex_split('/[\\s,]+/') %}

Learn more about the regex_split filter

replace

Replaces the specified text or placeholders with other values.

{{ 'I like %this% and %that%.'|replace({'%this%': 'apples', '%that%': 'bananas'}) }}

{{ variable|replace({'-': '%ndash;'}) }}

{{ 'Hi my name is Bob'|replace('Bob', 'Sam') }}

Learn more about the replace filter

reverse

Reverses an array, hash or string.

{% for post in posts|reverse %}
{% endfor %}

round

Rounds a number to a given precision using a specific rounding method.

{{ 42.55|round }}

{{ 42.55|round(1) }}

{{ 42.55|round(1, 'ceil') }}

rsort

Sorts an array in reverse order.

{% set array = array|rsort %}

Learn more about the rsort filter

rtrim

Strip whitespace (or other characters) from the end of a string.

{{ var|rtrim }}

slice

Extracts a slice of an array, hash or string.

{% for i in [1, 2, 3, 4]|slice(1, 2) %}
{% endfor %}

Learn more about the slice filter

snake

Takes a string and creates a lowercase version of it with words separated by underscores instead of spaces.

{{ "Apples and Pears"|snake }}

Learn more about the snake filter

sort

Sorts an array.

{% set array = array|sort %}

Learn more about the sort filter

split

Splits a string into an array by the passed delimiter.

{% set data = 'one,two,three'|split(',') %}

state_abbreviation

Gets the 2 letter state/province abbreviation for the variable value if the variable value is a valid state/province or state/province abbreviation.

{{ variable|state_abbreviation }}

state_data

Gets an array of state/province data for the variable value if the variable value is a valid state/province or state/province abbreviation.

The array contains the following information:
abbreviation: the 2 letter state/province abbreviation
name
: the full state/province name

{% set data = variable|state_data %}

state_name

Gets the full state/province name for the variable value if the variable value is a valid state/province or state/province abbreviation.

{{ variable|state_name }}

striptags

Strips HTML tags from the string.

{{ post.abstract|striptags }}

text2html

Converts a plain-text string to HTML characters. New line characters are converted to <br> tags.

{{ post.plainDescription|text2html }}

theme_url

Prepends the URL of the theme asset with the theme path. This is useful when using images, CSS or Javascript theme assets in the theme templates. It ensure that if the path to the theme changes then the links to the theme assets won't be broken.

<link rel="stylesheet" href="{{ 'css/index.css'|theme_url }}">

Learn more about the theme_url filter

time

Formats a timestamp to a given time format.

{{ post.publishedOnTimestamp|time('H:i A') }}

time_diff

Formats a timestamp as human readable time difference from now (e.g. 2 minutes ago, 5 hours ago or 6 days ago).

{{ post.createdOnTimestamp|time_diff }}

title

Converts a string to have the first letter of each word capitalized and all other characters lower case.

{{ post.postTitle|title }}

trim

Strips whitespace (or other characters) from the beginning and end of a string.

{{ ' BranchCMS is awesome! '|trim }}

truncate

Shortens a string to the specified length. This does not take HTML tags into consideration.

{{ var|truncate(20) }}

Learn more about the truncate filter

truncate_html

Shortens a string to a specified length and ensures that the HTML does not get broken.

{{ post.content|truncate_html(100) }}

Learn more about the truncate_html filter

ucfirst

Capitalizes the first character of a string and leaves all other characters alone.

{{ post.postTitle|ucfirst }}

ucwords

Capitalizes the first character of each work and leaves all other characters alone.

{{ product.productName|ucwords }}

unique

Gets the unique values from an array.

{% set unique = arrayVariable|unique %}

upper

Converts a string so that all characters are uppercase. 

{{ post.postTitle|upper }}

url

Makes sure that the URL path starts and ends with a slash if necessary and is a proper URL.

{{ profile.website|url }}

url_encode

Encodes a string to be part of a URL. Or, it converts an array to be a query string.

{{ variable|url_encode }}

{{ {'param': 'value', 'foo': 'bar'}|url_encode }}