user3826926
user3826926

Reputation: 21

How to add a delimiter in twig to a string?

i have time in format HHMM as string and would like to add " : " after hours. is there a simple filter to split string after two characters and add a delimiter?

Upvotes: 2

Views: 915

Answers (1)

Matteo
Matteo

Reputation: 39470

You can split by position like this

 {% set bar = "aabbcc"|split('', 2) %}
 {# bar contains ['aa', 'bb', 'cc'] #}

As described in the doc

So you can do something like:

{% set bar = "1203"|split('', 2) %}
{# bar contains ['12', '03'] #}

now let's do:

{{ bar[0]~":"~bar[1] }}

this will output:

12:03

Better if you build a macro or a TWIG extension with the function

Hope this help

Upvotes: 3

Related Questions