Last active
March 15, 2023 20:03
-
-
Save radarseven/20b05b0948a6e3a0e2e601752b63cdc1 to your computer and use it in GitHub Desktop.
Craft CMS - Twig macro for finding position of entry in Structure section.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# 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