Michael Emerson
Michael Emerson

Reputation: 1813

How to use substr with strstr in Twig

I'm working on a Symfony site which incorporates a scheduler, and on this scheduler there are tasks which have user's names on them. My client has requested that only the surname be shown but currently the database saves the name as a complete string named contactName.

I am currently using the following code in Twig to display the name:

schedule.user.contactName

I tried using the split command, which seemed to do what I want:

schedule.user.contactName|split(" ",1)

But this only returns an array, and I do not know how to take the surname from this.

Any help with this is appreciated - maybe there is an alternative way to do this?

Upvotes: 1

Views: 8755

Answers (2)

doydoy44
doydoy44

Reputation: 5772

Maybe you could try this:

schedule.user.contactName|split(' ', 2)|first 

Upvotes: 4

Alister Bulman
Alister Bulman

Reputation: 35139

There are two ways I can think of:

Set the output of the split function as a new variable, and since it's an array, you should be able to get name[1], or maybe name.1 from it for the 2nd part (if it exists, and your customer is not 'Cher', 'Prince', or the like).

It's probably easier to do it in two parts like this, rather than trying to combine it to a single statement.

{% set nameParts = schedule.user.contactName|split(" ",1) %}
{{ nameParts[1]|default(schedule.user.contactName) }}

You can also perform the split within the entity - getContactNameSurname() that does the split in PHP code, and returns the 2nd part.

Upvotes: 0

Related Questions