3

I want to join two variables in twig in the user.html.twig

{{ content.field_firstname }} {{ content.field_lastname }}

How can i output them on the same line and add a space between them using twig ?

Everytime i try, they show on two different lines ? and i don't want to use css just for this.

Is there any better way to do this ? Many thanks

  • 3
    Fields are wrapped in divs, divs have a block display by default. Using CSS is the easier solution, the alternative is overwriting templates for individual fields to remove the wrappers – Clive Sep 7 '16 at 16:34
5

{% set full_name = [content.field_firstname ~ ' ' ~ content.field_lastname] %}

Note: We use ~ in twig to concatenate two or more strings instead of "+"

  • Thank you for your answer, but the result that i get when i output {{ full_name }} is not the first name and last name but Array Array – usethe23 Sep 8 '16 at 8:05
  • Hope you are using the right variables. – Suraj k Sep 11 '16 at 10:16
  • Yes i am, when i output them indivisually they do work :S – usethe23 Sep 13 '16 at 14:23
  • I am not sure what kind of problem you are facing can you share your code. is it drupal8? – Suraj k Sep 16 '16 at 10:49
1

You might have to dig a little deeper depending on the field type. If you {{ kint(content) }} in the template, you should be able to dig down to the actual value.

You might be looking for one of the following:

{% set full_name = content.field_firstname.value ~ ' ' ~ content.field_lastname.value %}

{% set full_name = content.field_firstname.0['#markup'] ~ ' ' ~ content.field_lastname.0['#markup'] %}

Or something similar.

Without seeing your code/kint output, it's hard to say. But that should get you going in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.