Treat
Treat

Reputation: 192

How to cut off end in Twig

I have this code in my Twig template:

    <h2><a href="{{ wp.get_permalink(property.ID) }}">
            {% if property.meta._property_title.0 %}
                {{ property.meta._property_title.0 }}
            {% else %}
                {{ property.post_title }}
            {% endif %}
       </a></h2>

property.post_title will look like Some words / Other words / More words / 123

What I want to do is to display only the part until the first slash, so in this case only Some words

Is there anyone who can help me with this?

Upvotes: 0

Views: 660

Answers (2)

Tyralcori
Tyralcori

Reputation: 1047

Twig has the function, to split a string into array by your own delimiter:

{% set foo = "one,two,three"|split(',') %}

You can create a new var, and split on "/":

{% set splits = property.post_title|split('/') %}

Now you have a simple array, and can print the first part:

 <h2><a href="{{ wp.get_permalink(property.ID) }}">
        {% if property.meta._property_title.0 %}
            {{ property.meta._property_title.0 }}
        {% else %}
            {{ splits.0 }}
        {% endif %}
 </a></h2>

See http://twig.sensiolabs.org/doc/filters/split.html for more.

Upvotes: 2

Devatoria
Devatoria

Reputation: 685

This should work (if you do not want to declare a new twig variable).

{{ property.post_title|split('/')[0] }}

Upvotes: 2

Related Questions