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

Cavell Blood
  • 693
  • 6
  • 21
Daniel Park
  • 11
  • 1
  • 2

3 Answers3

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; }
Paul Grant
  • 31
  • 1
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.

carlcs
  • 36,220
  • 5
  • 62
  • 139
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.

Steve Abraham
  • 909
  • 6
  • 17
  • 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 09: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 09:33
  • I added pull request for option to keep html tags github – Vadim Goncharov Feb 13 '17 at 18:19