Meules
Meules

Reputation: 1389

Replace string variable inside loop

I have a loop in twig/symphony, like so:

{% for breadcrumb in page.breadcrumbs %}    
  <a href="{{ breadcrumb.url | url }}">{{ breadcrumb.title }}</a>
{% endfor %}

I'm trying to check the first variable in the for loop. If that equals Artists then the html part need to be replaced by a new piece of code.

So what I did was this:

 {% for breadcrumb in page.breadcrumbs %}

  {% if loop.first %}
  {% if breadcrumb.title == 'Artists' %}
  <a href="{{ 'artists' | url }}">{{ 'Artists' | t }}</a>{% else %}<a href="{{ breadcrumb.url | url }}">{{ breadcrumb.title }}</a>
  {% endif %}
  {% endif %}

  {% endfor %}

This works however when the bradcrumb path goes deeper then two levels then everything after the second level isn't shown anymore. So what I mean is this:

home > Artist > //nothing shown here anymore. Loop stops I think??

Instead of 

home > artists > category1 > subcategory 2

Does anyone know what I am doing wrong. Why does the loop stop with this code?

Upvotes: 0

Views: 81

Answers (2)

sjagr
sjagr

Reputation: 16502

The loop keeps going, but you've wrapped the entire output logic into the loop.first variable conditional.

You need to do this instead:

{% for breadcrumb in page.breadcrumbs %}
    {% if loop.first and breadcrumb.title == 'Artists' %}
        <a href="{{ 'artists' | url }}">{{ 'Artists' | t }}</a>
    {% else %}
        <a href="{{ breadcrumb.url | url }}">{{ breadcrumb.title }}</a>
    {% endif %}
{% endfor %}

This way you are checking for both the first iteration of the loop and whether or not the title is "Artists"

Upvotes: 1

devilcius
devilcius

Reputation: 1884

You're only checking the first iteration (first loop), and do nothing with the rest:

{% for breadcrumb in page.breadcrumbs %}

    {% if loop.first %}
        {% if breadcrumb.title == 'Artists' %}
            <a href="{{ 'artists' | url }}">{{ 'Artists' | t }}</a>
        {% else %}
            <a href="{{ breadcrumb.url | url }}">{{ breadcrumb.title }}</a>
        {% endif %}
   {% endif %}

{% endfor %}

Upvotes: 0

Related Questions