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

base64_decode

Decodes a base64 encoded value.

{{ value|base64_decode }}

Learn more about the base64_decode filter

base64_encode

Base 64 encodes a value. The value must be a string.

{{ value|base64_encode }}

Learn more about the base64_encode 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_diff

Gets the difference between now (or a passed date) and the date value the filter is applied to.

{{ post.createdOnTimestamp|time_ago }}

Learn more about the date_diff 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 statement. Useful for development.

{{ post|debug }}

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

debug_email

Outputs the results of a variable in a debug statement specifically formatted for using in emails. Useful when developing form notification emails.

{{ form.fields|debug_email }}

{{ form.fields|debug_email('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_basename

Parses the file path and returns just the basename value.

{{ '/path/to/my/file.pdf'|file_basename }}

Learn more about the file_basename filter

file_dirname

Parses the file path and returns just the dirname value.

{{ '/path/to/my/file.pdf'|file_dirname }}

Learn more about the file_dirname filter

file_extension

Parses the file path and returns just the file extension value.

{{ '/path/to/my/file.pdf'|file_extension }}

Learn more about the file_extension filter

file_name

Parses the file path and returns just the filename value.

{{ '/path/to/my/file.pdf'|file_name }}

Learn more about the file_name filter

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

intersect

Returns an array containing only the values that are in both arrays.

{% set myPets = ['dog', 'cat', 'snake', 'elephant', 'fish'] %}
{% set yourPets = ['snake', 'camel', 'fish', 'shark'] %}
{% set samePets = myPets|intersect(yourPets) %}

Learn more about the intersect filter

intersect_assoc

Returns an array containing only the values that are in both arrays. The array keys are also used in the comparison.

{% set myColors = {'g': 'green', 'b': 'blue', 'y': 'yellow', 'r': 'red'} %}
{% set yourColors = {'b': 'brown', 'g': 'green', 'x': 'yellow'} %}
{% set sameColors = myColors|intersect_assoc(yourColors) %}

Learn more about the intersect_assoc filter

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_decode

Converts a JSON string into an array of values.

{% set data = jsonString|json_decode %}

json_encode

Returns the JSON representation of a value. If the value is a string then it'll be wrapped in double-quotes. If it's a number or boolean then no change is made. If it's an array or object then it'll be converted to the JSON equivalent. 

{{ post.postTitle|json_encode }}

Learn more about the json_encode filter

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

kintersect

Returns an array containing only the values that are in the first array whose keys are also in the second array. The values are not compared.

{% set myColors = {'blue': '5', 'red': '15', 'green': '2'} %}
{% set yourColors = {'red': '2', 'black': '3', 'green': '30'} %}
{% set same = myColors|kintersect(yourColors) %}

Learn more about the kintersect filter

kmerge

Merges two arrays together while preserving their keys (including numeric keys).

{% set array = {1: 'One', 2: 'Two', 3: 'Three', 'four': 'Four string'} %}
{% set array2 = {1: 'One2', 2: 'Two2', 4: 'Four', 5: 'Five'} %}
{% set array = array|kmerge(array2) %}

Learn more about the kmerge filter

kmerge_deep

Merges two arrays together recursively while preserving their keys (including numeric keys).

{% set array = {1: 'One', 2: 'Two', 3: ['Three', 'Three is great'], 'four': 'Four string', 'five': {32: 'numeric key', 'string': 'string key'}} %}
{% set array2 = {2: 'New Two', 3: ['Another three'], 'four': 'New Four string', 'five': {32: 'new numeric key'}, 'six': 'I will stay'} %}
{% set array = array|kmerge_deep(array2) %}

Learn more about the kmerge_deep 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 }}

Learn more about the last filter

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

merge_deep

Merges two arrays together recursively.

{% set array = {1: 'One', 2: 'Two', 3: ['Three', 'Three is great'], 'four': 'Four string', 'five': {32: 'numeric key', 'string': 'string key'}} %}
{% set array2 = {1: 'One2', 2: 'Two2', 4: 'Four', 5: 'Five'} %}
{% set array = array|merge_deep(array2) %}

Learn more about the merge_deep filter

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

push

Pushes a value to the end of an array. It can sometimes be simpler than using the merge filter.

{% set animals = [] %}
{% set animals = animals|push('dog') %}
{% set animals = animals|push('cat') %}
{% set animals = animals|push('fish') %}

Learn more about the push 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_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 }}

shuffle

Randomizes the order of elements in an array.\ and returns the result.

{% set newValue = value|shuffle %}

Learn more about the shuffle filter

slice

Extracts a slice of an array, hash or string.

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

sort_by_key

Sort a multi-dimensional array by a specific value in a child array. The value is specified by the array key. The sorting is case sensitive.

By default the values are sorted in ascending order. You can pass a second parameter to sort in descending order.

{% set myArray = myArray|sort_by_key('age') %}
{% set myArray = myArray|sort_by_key('age', 'desc') %}

sort_ci_by_key

Sort a multi-dimensional array in a case insensitive way by a specific value in a child array. The value is specified by the array key.

By default the values are sorted in ascending order. You can pass a second parameter to sort in descending order.

{% set myArray = myArray|sort_ci_by_key('age') %}
{% set myArray = myArray|sort_ci_by_key('age', 'desc') %}

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. Newline characters are converted to <br> tags. URL are also converted to links.

{{ post.plainDescription|text2html }}

Learn more about the text2html filter

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_ago

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

{{ post.createdOnTimestamp|time_ago }}

Learn more about the time_ago filter

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_domain

Parses the URL and returns just the domain value.

{{ 'https://www.branchcms.com'|url_domain }}

Learn more about the url_domain filter

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

url_host

Parses the URL and returns just the host value.

{{ 'https://www.branchcms.com'|url_host }}

Learn more about the url_host filter

url_suffix

Parses the URL and returns just the domain name suffix (i.e. the top-level domain and second-level domain if it exists).

{{ myUrl|url_suffix }}

Learn more about the url_suffix filter

values

Gets just the values of an array without any specific keys.

{% set array = {'foo': 'Foo', 'bar': 'Bar'} %}
{% set values = array|values %}

Learn more about the values filter