Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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.

share|improve this question
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 at 5:17

2 Answers 2

{% 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')

share|improve this answer
    
Thank you - I thought that was the first thing I tried, but works great! –  Andrew Jul 3 at 18:02

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.

share|improve this answer
    
Awesome - thank you. –  Andrew Jul 17 at 4:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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