Patrick Patrick - 3 months ago 28
Twig Question

What is the correct way to concatenate and trim in TWIG

I'm new to TWIG. I can do this in PHP, but I'm looking for the right way to do it in the template using TWIG.

Controller code:

public function indexAction()
{
$em = $this->getDoctrine()
->getEntityManager();
$properties = $em->getRepository('MainBundle:Property')->findAll();

return $this->render('MainBundle:Admin:index.html.twig', array(
'bmproperty' => $properties,
));
}


TWIG Template:

{% for property in bmproperty %}
<div {% if property.hasHoaLien == false %}class="nolien"{% else %}class="haslien"{% endif %}>
<ul><li><a href="{{ path('MainBundle_Property_Edit', {'id' : property.id}) }}">
{% if property.houseNumber is null %} {{ property.street }}
Lot #{{ property.lotNumber }}
{% else %}
{{ property.houseNumber }} {{ property.street }}
{% endif %}
</a>
</li><li>
{% if property.user is not empty %}
{% for user in property.user %}
{{ user.fullname }},
{% endfor %}
{% else %}
{{ property.status }}
{% endif %}
</li><li>{{ property.type }}</li>{% if property.isOccupied == true %}<li>Occupied</li>{% else %}<li>Vacant</li>{% endif %}{% if property.inArrears == true %}<li>Yes</li>{% else %}<li>No</li>{% endif %}</ul>
</div>
{% endfor %}


My problem is with this snippet in the above code:

{% for user in property.user %}
{{ user.fullname }},
{% endfor %}


There are two user names on this line and I'm simply trying to separate them with a comma and then trim the last comma.

Do I assign the two users to a variable in the template then just use the TRIM option in TWIG? If so, I'm not sure how to concatenate them to a single variable in TWIG template.

Answer

You can't use join with a non array variable. In the example you use:

{{ property.user.fullname|join(',') }}

Join works as a php implode function, so the argument must be an array. fullname is not a member of property.user, but a member of each of the property.user.0.fullname, property.user.1.fullname

To cancatenate 2 or more string you can use the ~ operator

{{ property.user.0.fullname ~', ' ~ property.user.1.fullname }}

My approach would be to add a variable that holds the names, and then implode it after the for

{% set arr ={} %
{% for key,user in property.user %}
  {% set arr = arr|merge({key: user.fullname}) %}  
{% endfor %}
{{ arr|join(',') }}