Skip to content

Instantly share code, notes, and snippets.

@radarseven
Last active March 15, 2023 20:03
Show Gist options
  • Save radarseven/20b05b0948a6e3a0e2e601752b63cdc1 to your computer and use it in GitHub Desktop.
Save radarseven/20b05b0948a6e3a0e2e601752b63cdc1 to your computer and use it in GitHub Desktop.
Craft CMS - Twig macro for finding position of entry in Structure section.
{# Get the position of an entry in a Structure section. #}
{% macro getEntryPosition(entry, level) %}
{% spaceless %}
{% if entry is defined and entry|length and entry.section is defined and entry.section.type == 'structure' %}
{% set siblingIds = craft.entries.section(entry.section.handle).level(level|default(2)).ids() %}
{% set position = null %}
{% for siblingId in siblingIds %}
{% if position is null %}
{% set position = siblingId == entry.id ? loop.index : null %}
{% endif %}
{% endfor %}
{# Begin macro output #}
{# ------------------ #}
{# Return just the position #}
{{ position }}
{# ------------------ #}
{# End macro output #}
{% endif %}
{% endspaceless %}
{% endmacro %}
{# Get the position of an entry in a Structure section based on it's parent entry. #}
{% macro getEntryPositionFromParent(entry) %}
{% spaceless %}
{% if entry is defined and entry|length and entry.section is defined and entry.section.type == 'structure' %}
{% set siblingIds = entry.parent.children.ids %}
{% set position = null %}
{% for siblingId in siblingIds %}
{% if position is null %}
{% set position = siblingId == entry.id ? loop.index : null %}
{% endif %}
{% endfor %}
{# Begin macro output #}
{# ------------------ #}
{# Return just the position #}
{{ position }}
{# ------------------ #}
{# End macro output #}
{% endif %}
{% endspaceless %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment