Reputation: 840
I there,
I'm trying to find the last character for a string in twig. What I need to do is that if the string ends with s then I only add ' Zone and if the string doesn't have an s at the end I should add 's Zone.
E.g., "Charles's Zone" should become "Charles' Zone".
Thanks a lot
Upvotes: 2
Views: 7897
Reputation: 81
From version 3, you can use slice
filter like this:
{{ 'Charles\'s'|slice(0, -1) }}
{# outputs Charles' #}
or with shorthand notation:
{{ 'Charles\'s'[:-1] }}
{# outputs Charles' #}
Full Twig docs for slice
: https://twig.symfony.com/doc/3.x/filters/slice.html
Upvotes: 0
Reputation: 46
using last
{{ [1, 2, 3, 4]|last }}
{# outputs 4 #}
{{ { a: 1, b: 2, c: 3, d: 4 }|last }}
{# outputs 4 #}
{{ '1234'|last }}
{# outputs 4 #}
Upvotes: 3
Reputation: 7428
{% set test_string = 'asdfs' %}
{% set test_string = test_string ~ (test_string|last == 's' ? "' " : "'s ") ~ "Zone" %}
Upvotes: 3
Reputation: 840
I figured a workaround:
{% set title = user_name ~ "\'s zone" %}
{% set replace_value_var= "s\'s zone" %}
{% set replace_with_value_var = "s\' zone"%}
{% set MyTitle = title|replace({ (replace_value_var): replace_with_value_var }) %}
Upvotes: 0