1

If I enter a query into the search bar I would like to see an excerpt (let's say 140 characters) of each entry that is related to the query.

Here is what I use on the search result page to display the results.

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score') %}

{% if entries|length %}
<p>{{ entries|length }} results:</p>

<ul>
    {% for entry in entries %}
        <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
    {% endfor %}
</ul>
{% else %}
<p>Your search for “{{ query }}” didn’t return any results.</p>
{% endif %}

How do I add entry excerpts like: https://craftcms.com/search?q=entry

3

Have a look at the slice filter. To return 140 characters max. you would do something like this:

{% if entry.body %}
    {{ entry.body|slice(0, 140) }}
{% endif %}

See this other question on a similar topic if you want to apply this on a rich text field. Because this solution only works with plain text.

  • This thew an exception for me. Calling unknown method: craft\elements\Entry::body() I am using craft 3 – Radmation Sep 19 '18 at 15:58
  • Is that your field handle, body? – carlcs Sep 19 '18 at 16:05
3

Looking at the Happy Lager demo site there's a Short Description field, which functions as an excerpt for indexes and search results. I imagine P&T use something similar for the Craft docs.

You could also force your results onto one line and trim it with css, which is how P&T do it on the Craft docs search results page:

li { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
2

I use Trimmer for this, it's pretty much the only plugin I use these days.

I don't know for sure, but I suspect P&T may use an 'excerpt' field to store a short sentence for use on the search results page, rather than cropping from longer copy.

  • Do I understand it right and this does remove all HTML tags? Again a deal breaker for rich text fields but otherwise a great little plugin. I especially like the option to trim before full words only. – carlcs Nov 19 '14 at 9:25
  • Yes, it does strip HTML. There was a plugin for EE that would allow HTML and close any tags left open after trimming, I must try and find it to see if it can be/has been ported. – Steve Abraham Nov 19 '14 at 9:33
  • I added pull request for option to keep html tags github – Vadim Goncharov Feb 13 '17 at 18:19

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.