Skip to main content

Search Integration

Distill can add the results of a query to a search index, so the individual sections of a page appear as their own search results rather than the page as a whole. You can then use fragment URLs to link straight to the matching section. Items from entries and terms are supported.


Setting Up

There are three parts to it: a still that defines the query, a searchable in your index config that points at it, and a template that knows how to render the results.

First the still, which decides what gets indexed. This one picks out every section set that's a direct child of the builder field:

// app/Stills/Sections.php
namespace App\Stills;

use JackSleight\StatamicDistill\Stills\Still;

class Sections extends Still
{
    public function apply($query, $values)
    {
        $query->path('builder.*')->type('set:section');
    }
}

Then add a distill: searchable to an index in config/statamic/search.php. The format is distill:collection:[handle]:[still] for entries or distill:taxonomy:[handle]:[still] for terms, and the fields are read from each item's own data:

'indexes' => [
    'default' => [
        'driver' => 'local',
        'searchables' => ['collection:pages', 'distill:collection:pages:sections'],
        'fields' => ['title', 'heading', 'text'],
    ],
],

Here every section set in the pages collection will be indexed by its heading and text fields, alongside the pages themselves. Then run the usual command to build the index:

php please search:update

Rendering Results

Items come back from the {{ search:results }} tag mixed in with the normal results. Their result_type is distill: followed by the item type, they include all of the item's own fields, and the info object tells you which entry they came from:

{{ search:results }}
    {{ if result_type === 'distill:set:section' }}
        <a href="{{ info:source:url }}#{{ id }}">{{ heading }}</a>
    {{ else }}
        <a href="{{ url }}">{{ title }}</a>
    {{ /if }}
{{ /search:results }}

For the fragment link to work you'll need to output the set's id on the section in your page template, something like <section id="{{ id }}">.


Keeping the Index Updated

Distill listens for entries and terms being saved or deleted and updates the index to match, so a section that's added, changed or removed is reflected straight away without a full reindex.