2

I have an {% include%} which displays entries from a structure. This {% include%} is displayed on the homepage and other entries throughout the site.

On the homepage, I'd like the include to show a specific title. On the other entries, I'd like it to show a different title.

Here's what I've tried:

{% if craft.request.getUrl() == "/" %}
    <h2>Homepage Title</h2>
{% else %}
    <h2>Other Title</h2>
{% endif %}

Both titles appear on the homepage, but the {% else %} title appears correctly on the other entries. What am I doing wrong here?

Here's the code from the include file:

<div class="grid specialties">

    {% if craft.request.getUrl() == siteUrl %}
        <h2>Homepage Title</h2>
    {% else %}
        <h2>Other Title</h2>
    {% endif %}

    {% for entry in craft.entries.section('feed').find() %}
        <article class="fifth">
            <a href="{{ entry.url }}">
                {% set image = entry.icon.first() %}
                    <img src="{{ image.url }}" alt="{{ image.title }}">
                {% endif %}
                <h3>{{ entry.title }}</h3>
            </a>
        </article>
    {% endfor %}

</div>

Here's the homepage code:

{% extends "_layout" %}
{% block content %}
    {% include "_includes/layout_builder" %}
    {% include "_includes/specialties" %}
{% endblock %}

2 Answers 2

6

Both titles can not appear in your condition(on the homepage). Always only one true statement is executed.

To your problem: there is one global variable that solves your problem.

{% if craft.request.getUrl() == siteUrl %}
    <h2>Homepage Title</h2>
{% else %}
    <h2>Other Title</h2>
{% endif %}

There is also the link How Craft Determines the Site URL.

10
  • Thanks for this. The current solution you've suggested repeats <h2>Homepage Title</h2> twice on the homepage. Any ideas?
    – Sam
    Commented Sep 5, 2017 at 21:13
  • Let me see the code and I may help you better. Commented Sep 5, 2017 at 21:17
  • The code from my question has been placed within an include (via root/_includes/feed.html). The include sits on the homepage like so {% include "_includes/feed" %}.
    – Sam
    Commented Sep 5, 2017 at 21:28
  • Is only the code from question in your feed.html? Commented Sep 5, 2017 at 22:01
  • 1
    Don't. It gives you a lesson. A lesson to know and understand your code. It makes life easier next time. Commented Sep 12, 2017 at 19:29
2

I like the solution above. I'd add craft.app.language if you're working on a localized site.

{% if craft.app.request.absoluteUrl == siteUrl or craft.app.request.absoluteUrl == siteUrl + craft.app.language %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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