4

I'm pretty new to Twig and I know the level here is far above my question, but thank you in advance...

I'm designing a site with sponsor logos on the homepage, each sponsor is an entry in a channel of sponsors. I have a lightswitch field on the entry page called 'showOnHome'. I've tried "if" statements and conditionals in the loop, but have only got to where it shows the first entry and breaks the loop.

The following works to get all of the entries,

<ul>
    {% for entry in craft.entries.section('sponsors') %}
        {% for image in entry.sponsorlogo %}

            <li><a href="{{ entry.getUrl }}"><img src="{{ image.getUrl() }}" alt="{{ image.title }}"</a></li>

        {% endfor %}
    {% endfor %}
</ul>

How do I only get entries where showOnHome == '1'?

Thank you in advance for helping the rookie.

1
  • 2
    I think I can speak for everyone and say that the level here is at any level you need. Everyone is very happy to help and teach.
    – Anna_MediaGirl
    Jul 4 '14 at 5:17
8

{% for entry in craft.entries.section('sponsors').showOnHome('1') %}

The .showOnHome('1') restricts your query to ones with the lightswitch on.

If you wanted only the ones with the lightswitch off, you would use .showOnHome('not 1')

1
  • Thank you - I thought that was the first thing I tried, but works great!
    – Andrew
    Jul 3 '14 at 18:02
3

While Marion’s answer is definitely the right way to go about this, since you’re new with Twig I’ll show you how you could also do this with a Twig conditional.

You could use an {% if %} tag to check if your showOnHome field is enabled.

<ul>
    {% for entry in craft.entries.section('sponsors') %}

        {% if entry.showOnHome %}

            {% for image in entry.sponsorlogo %}
                <li><a href="{{ entry.getUrl }}"><img src="{{ image.getUrl() }}" alt="{{ image.title }}"</a></li>
            {% endfor %}

        {% endif %}

    {% endfor %}
</ul>

Hope that helps. Again, using the showOnHome(1) parameter on craft.entries query is a much better way to go, since you will be saving Craft the trouble of fetching those entries to begin with.

1
  • Awesome - thank you.
    – Andrew
    Jul 17 '14 at 4:12

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.