15

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

11

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:

_search-excerpts/default.html
_search-excerpts/sectionA.html
_search-excerpts/sectionB.html
_search-excerpts/sectionC.html
9

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 %}
  • 1
    Worth 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 Jun 13 '14 at 22:59

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.