Skip to content

Instantly share code, notes, and snippets.

@imagehat
Forked from radarseven/structureHelper.twig
Created March 16, 2026 22:30
Show Gist options
  • Select an option

  • Save imagehat/3d3a9fc323518d6fd20d46882b5b7b33 to your computer and use it in GitHub Desktop.

Select an option

Save imagehat/3d3a9fc323518d6fd20d46882b5b7b33 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