How can I display search "excerpts" from multiple sections?



How do I create search result page "excerpts" when there are multiple sections/fields that need to be represented?


Posted 2014-06-12T17:02:14.123

Reputation: 1 735



This can be accomplished using a conditional:

{% if entry.section == 'sectionA' %}
    {{ entry.sectionAField }}
{% elseif entry.section == 'sectionB' %}
    {{ entry.sectionBField }}
{% endif %}

or a switch statement:

{% switch entry.section %}
    {% case "sectionA" %}
       {{ entry.sectionAField }}
    {% case "sectionB" %}
       {{ entry.sectionBField }}
{% endswitch %}


Posted 2014-06-12T17:02:14.123

Reputation: 1 735

1Worth noting that one of the big advantages of being able to share field across sections is that a lot of the time the excerpt field will be the same so no need for the if's but when it's not you got the right idea – Keith Mancuso – 2014-06-13T22:59:08.110


There is no way at present to delegate a field as the search excerpt field in Craft, so it needs to be handled by the search results template. It is possible to use conditionals but this can bloat the template, especially when there are multiple sections and each section outputs different fields in different ways, so I prefer to create dedicated search excerpt templates and include them in the search results template as follows:

{% include ['_search-excerpts/' ~ entry.section.handle, '_search-excerpts/default'] %}

The above code will render the section's dedicated search excerpt template if it exists in a folder called _search-excerpts, otherwise it will render the default search excerpt template which can contain for example:

<a href="{{ entry.url }}">{{ entry.title }}</a>

The resulting folder structure would then look like this:


Ben Croker

Posted 2014-06-12T17:02:14.123

Reputation: 3 178