Resources
Resources
Search Form
To add a search form to your website, create an HTML form which submits to a /search/results
page, passing the search query as a q
query string parameter.
<form action="{{ url('search/results') }}">
<input type="search" name="q" aria-label="Search" placeholder="Search">
<button type="submit">Go</button>
</form>
Then create a search/results.twig
template, which will pass the q
query string value into an entry query’s search
parameter.
<h1>Search Results</h1>
{% set searchQuery = craft.app.request.getParam('q') %}
{% set entries = craft.entries()
.search(searchQuery)
.orderBy('score')
.all() %}
{% 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 “{{ searchQuery }}” didn’t return any results.</p>
{% endif %}