2

I'd like to output a special link in level 1 upon current top-level entry doesn't have any entries at level 3. If It have move that special link one level above.

To picture it:

  • Page 1
    • Subpage 1
    • Subpage 2
    • Special link A
  • Page 2
    • Subpage 1
      • Subpage 1.1
      • Special link A

Currently I didn't have any difficulties with level 2:

{% set lvl = entry.level %} 
{% if lvl == 2 and entry.children|length %}
    A link
{% endif %}

To set that special link at level 1 is. Most logical way to me is to use EntryModel's method getDescendants( distance ) as I don't have to set any variable. If I understand it correctly It should get descendant entries at given level? of a current entry's variable. When I set to (distance) other integer than 1 let's say 2 It prints out all entries from second level including level 2. So It's unclear to me what distance does in this case.

{% if lvl == 1 and entry.getDescendants(2)|length %}
    A link
{% endif %}

Argument is true even if there are no descendant entries of second level. Because When looping in It prints all entries from second level up including second level as I mentioned before.

Or I can't use this method?

1 Answer 1

3

To make it works I had to query in the section for descendant entries at level 3 of a current entry variable.

{% set products = craft.entries.section('products') %}

{% if lvl == 1 and products.descendantOf(entry).level(3).first()|length %}
    // If the above statment is true we don't want that special link at level 1
{% elseif lvl == 1 %}
    // A special link
{% endif %}


{% if lvl == 2 and entry.children|length %}
    // A special link
{% endif %}

I welcome a smarter solution.

Updated: Thanks to @carlcs comment a performance has been enhanced

{% if lvl == 1 and products.descendantOf(entry).level(3).total() > 0 %}
    // If the above statment is true we don't want that special link at level 1
{% elseif lvl == 1 %}
    // A special link
{% endif %}


{% if lvl == 2 and entry.children.total() > 0 %}
    // A special link
{% endif %}
1
  • 1
    This is a good solution, to improve performance you could just query for the amount of records in your conditionals products.descendantOf(entry).level(3).total() and entry.children.total(), as you’re not interested in the entry data at all.
    – carlcs
    Commented Dec 13, 2016 at 15:27

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.