1

My setup

I'd like to show a navigation menu listing all my page entries. In my layout file, I include a template for the navigation:

_layout.twig:

    <main>
      <section id="nav">
        {% include "_includes/navigation.twig" %}
      </section>

      <section id="content">
        {% block content %}
        {% endblock %}
      </section>
    </main>

The current page is shown in the content block.

My question

Is there a way to globally access the currently viewed page, from inside the navigation.twig template. That way I could do:

{% set currentPageId = SOME_COOL_GLOBAL_FUNCTION %}
{% set pages = craft.entries.section('pages').id('not ' ~ currentPageId).all() %}
<nav id="navigation">
    <ul>
        {% for page in pages %}
            <li>{{ page.getLink() }}</li>
        {% endfor %}
    </ul>
</nav>
2

To me it looks like the entries in the section with the handle pages have their own URLs. This means that if you visit a URL that belongs to an entry in that section Craft will automatically make that entry available in the template as the entry variable. That being said your solution is in this case:

{% set currentPageId = entry.id %}
{% set pages = craft.entries.section('pages').id('not ' ~ currentPageId).all() %}
<nav id="navigation">
    <ul>
        {% for page in pages %}
            <li>{{ page.getLink() }}</li>
        {% endfor %}
    </ul>
</nav>

Or as an alternative:

{% set pages = craft.entries.section('pages').all() %}
<nav id="navigation">
    <ul>
        {% for page in pages if page.id != entry.id %}
            <li>{{ page.getLink() }}</li>
        {% endfor %}
    </ul>
</nav>

Here is a read about how Twig handles variable scope if you ask yourself why the entry variable is available in the included template: https://nystudio107.com/blog/twig-processing-order-and-scope

Also, here is a link to Twig's docs on conditional for loops: https://twig.symfony.com/doc/2.x/tags/for.html#adding-a-condition

| improve this answer | |
  • Thanks so much for the answer, and the explanation link too! – MonsieurNinja Jun 8 at 17:48

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.