search results paginate

 avatar
tommydalton
twig
a month ago
1.8 kB
4
Indexable
Never
{% set query = craft.app.request.getQueryParam('q') %}
{% set entries = craft.entries()
    .search(query)
    .section('yourSectionHandle') # Optional: Target specific section(s)
    .limit(12)
    .all() %}
<h1>Search Results</h1>
{% if query %}
    <p>Showing results for: "{{ query }}"</p>
{% endif %}
{% if entries|length %}
    <ul>
        {% for entry in entries %}
            <li>
                <a href="{{ entry.url }}">{{ entry.title }}</a>
                {# Include any other information you want to display #}
            </li>
        {% endfor %}
    </ul>
{% else %}
    <p>No results found for "{{ query }}".</p>
{% endif %}
```
### 3. Adding Pagination
To add pagination to your search results, you'll need to handle the pagination logic and adjust your template accordingly.
Replace the `.all()` method with `.paginate()` to handle pagination while retrieving entries. Let's adjust and add pagination:
```twig
{% set query = craft.app.request.getQueryParam('q') %}
{% set pageInfo = craft.entries()
    .search(query)
    .section('yourSectionHandle')
    .limit(12)
    .paginate() %}
{% set entries = pageInfo.getPageResults() %}
{% set currentPage = pageInfo.currentPage %}
{% set totalPages = pageInfo.totalPages %}
{# Rest of the search results template #}
{% if totalPages > 1 %}
    <nav class="pagination">
        {% if pageInfo.prevUrl %}
            <a href="{{ pageInfo.getPrevUrl() }}" rel="prev">Previous</a>
        {% endif %}
        {% for page in 1..totalPages %}
            <a href="{{ pageInfo.getPageUrl(page) }}" {% if page == currentPage %}class="active"{% endif %}>{{ page }}</a>
        {% endfor %}
        {% if pageInfo.nextUrl %}
            <a href="{{ pageInfo.getNextUrl() }}" rel="next">Next</a>
        {% endif %}
    </nav>
{% endif %}
Leave a Comment