3

So, I'm newer to Craft, and so I need to figure out the best way to set up a portfolio page with child entries. I've set up a structure, but I need the parent page to load a different template than _entry.html. I still haven't been able to figure out a good solution for this, so any help would be great.

Thanks!

7

First, I'd recommend that you have a total of 3 templates: _child.html for your child entries, _parent.html for your parent entries, and finally _entry.html which will basically work as a "controller" template (the only code contained in _entry.html should be the code that includes either the child or parent templates). You can, of course, name the templates whatever you want, but make sure that the Section's entry template is pointing to _entry.html.

Then, put this in your _entry.html file:

{% switch entry.level %}
    {% case 1 %}
        {% include '_parent.html' %}
    {% default %}
        {% include '_child.html' %}
{% endswitch %}

What the above does, is simply to look at the entry.level attribute, which returns the level your Structure entry is at. Top level entries are level 1, so for a simple 2-level Structure, this may work.

If you need something more flexible, where a "parent" template should be loaded unrelated to levels but based on whether an entry has children or not, you could do something like this (also in entry.html):

{% if entry.children|length %}
    {% include '_parent.html' %}
{% else %}
    {% include '_child.html' %}
{% endif %}

Another option is to test for an entry's parent property instead (i.e. if an entry has a parent entry, it should load the child template):

{% if entry.parent %}
    {% include '_child.html' %}
{% else %}
    {% include '_parent.html' %}
{% endif %}

Note: You may need to correct the paths to your templates for the examples above – the {% include %} always works relative to your /templates folder, so if your templates actually live inside /templates/news, you'd have to use {% include 'news/_parent.html' %} (even if _entry.html and _parent.html is inside the same folder).

  • How do I only show the children in _parent.html? – Jesse Winton Aug 7 '16 at 21:11
  • You should probably create a new question for that, @JesseWinton. – Mats Mikkel Rummelhoff Aug 8 '16 at 4:53

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.