Claude Skill

ux-pagination

Symfony UX Pagination: paginate Doctrine queries, arrays and API results with numbered links or cursors. Use for filtered lists, offset, lookahead and signed cursor pagination, PaginatorInterface, ux_pagination(), twig:ux:pagination, Twig themes and ComponentWithPaginationTrait.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Download smnandre-symfony-ux-skills-skills_ux-pagination-78c25ed.zip · 14 KB

Install

skills CLI npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/ux-pagination
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
Git git clone https://github.com/smnandre/symfony-ux-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

UX Pagination

One lazy, request-aware API to paginate arrays, Doctrine ORM and DBAL queries, and custom data sources. It validates ?page= and ?cursor=, keeps the current filters in every link, and renders accessible <nav> markup with real links, served as plain HTML.

Since Symfony UX 3.5+. The package is experimental: its API may still change.

Installation

composer require symfony/ux-pagination

Until the Flex recipe is published, register Symfony\UX\Pagination\UXPaginationBundle::class => ['all' => true] in config/bundles.php. Requires PHP 8.4+, Symfony 7.4 or 8.x, TwigBundle and Twig 3.10.3+. Doctrine ORM 3, DBAL 4.4+, TwigComponent and LiveComponent are optional.

Optional stylesheet for the default theme:

{# AssetMapper #}
<link rel="stylesheet" href="{{ asset('@symfony/ux-pagination/style.min.css') }}">

With Encore: npm install @symfony/ux-pagination, then import '@symfony/ux-pagination/style.min.css';.

Quick Start

use Symfony\UX\Pagination\PaginatorInterface;

#[Route('/products', name: 'product_index')]
public function index(ProductRepository $repository, PaginatorInterface $paginator): Response
{
    $products = $paginator->paginate($repository->createQueryBuilder('product'));

    return $this->render('product/index.html.twig', ['products' => $products]);
}
{% for product in products %}
    <article>{{ product.name }}</article>
{% else %}
    <p>No product.</p>
{% endfor %}

{{ ux_pagination(products) }}
{# or, with TwigComponent: <twig:ux:pagination :pagination="products" /> #}

The page comes from the page route attribute, then the page query parameter, then defaults to 1. paginate(page: 3) bypasses the request. Query parameters (filters) are preserved in generated links by default.

Choose a Strategy

The screen needs... Strategy Builder
Exact total, numbered links Offset query($source) (or paginate($source))
Only previous/next, no count query Lookahead query($source)->lookahead()
Stable traversal of a large or changing set Cursor cursor($source)->orderBy([...], 'DESC')
// Offset with a sliding window of 5 pages
$products = $paginator->query($qb)->perPage(20)->sliding(size: 5)->paginate();

// Lookahead: fetches perPage + 1 rows, totals are null
$activity = $paginator->query($qb)->perPage(30)->lookahead()->paginate();

// Cursor: signed opaque tokens in ?cursor=, no count, no page numbers
$entries = $paginator
    ->cursor($repository->createQueryBuilder('entry'))   // no orderBy() on the source
    ->orderBy(['createdAt', 'id'], 'DESC')               // unique tie-breaker last
    ->perPage(50)
    ->paginate();

All three return iterable results; templates that only iterate and render ux_pagination() work with any of them. Deep offsets are rejected above max_offset (100,000 by default).

For sort order, tie-breakers and cursor invalidation, check the cursor pagination troubleshooting guide.

Builder Essentials

Builders are immutable; finish with ->paginate():

$products = $paginator
    ->query($repository->listQuery($category))
    ->perPage(12)
    ->throwOnOutOfRange()                  // count now, 404 past the last page
    ->excludeQueryParameters('debug')      // drop a parameter from links
    ->fragment('results')                  // #results on every link
    ->paginate();
  • total(int|callable): provide the exact total (required for GROUP BY, HAVING, multiple roots).
  • pageParameter('orders_page'): one parameter per list when a page shows several lists.
  • route('name', [...]), path('/x'), queryParameters([...]), discardQueryString(): control link URLs.
  • fromCallbacks(slice: fn (int $offset, int $limit) => ..., count: fn () => ...): paginate an API or search engine.

Configuration

# config/packages/ux_pagination.yaml
ux_pagination:
    items_per_page: 20
    max_offset: 100000
    navigation:
        mode: sliding        # sliding | fixed | full
        size: 5
    theme: '@UXPagination/theme/default.html.twig'
    paginators:
        products:            # autowire as PaginatorInterface $productsPaginator
            items_per_page: 12

Named paginators inherit the root options. Inject them by argument name ($productsPaginator) or with #[Target('products')].

Rendering

Built-in themes: @UXPagination/theme/default.html.twig, bootstrap.html.twig (Bootstrap 5), tailwind.html.twig. They render numbered pages for offset results and only previous/next for lookahead and cursor results, and nothing at all when there is a single page.

{{ ux_pagination(
    products,
    {class: 'product-pagination', 'aria-label': 'Product results'},
    theme: '@UXPagination/theme/tailwind.html.twig',
    show_info: false,
    navigation_attributes: {class: 'controls'},
    link_attributes: {class: 'link'},
) }}

With Tailwind, add @source "../../vendor/symfony/ux-pagination/templates"; to your CSS (Tailwind 4) or the vendor path to content (Tailwind 3).

LiveComponent

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\Pagination\LiveComponent\ComponentWithPaginationTrait;
use Symfony\UX\Pagination\PaginationBuilder;
use Symfony\UX\Pagination\PaginatorInterface;

#[AsLiveComponent]
final class ProductList
{
    use DefaultActionTrait;
    use ComponentWithPaginationTrait;

    #[LiveProp(writable: true, url: true, onUpdated: 'onQueryUpdated')]
    public string $query = '';

    public function __construct(
        private readonly ProductRepository $products,
        private readonly PaginatorInterface $paginator,
    ) {}

    protected function createPagination(): PaginationBuilder
    {
        return $this->paginator->query($this->products->searchQuery($this->query));
    }

    public function onQueryUpdated(): void
    {
        $this->resetPage();
    }
}
<div {{ attributes }}>
    <input type="search" data-model="debounce(300)|query">
    {% for product in this.pagination %}<article>{{ product.name }}</article>{% endfor %}
    {{ ux_pagination(this.pagination, link_attributes: this.paginationLinkAttributes) }}
</div>

Numbered pagination only (offset or lookahead). Links keep a real href, so they keep working even before LiveComponent connects.

Key Principles

Ask what the screen promises. Offset only when users see a total or page numbers; lookahead when "next" is enough; cursor when rows move during browsing.

Every cursor order ends with a unique field. ['createdAt', 'id'], one direction for all fields, no ORDER BY on the source query.

The page size belongs to the application. There is no visitor-controlled per-page parameter; use items_per_page or perPage().

Links stay links. Turbo Frames, Turbo Drive and LiveComponent enhance them; without JavaScript, every link still works.

References

Demos

See Also

  • turbo: wrap the list and ux_pagination() in a <turbo-frame> to update only the results.
  • live-component: ComponentWithPaginationTrait for reactive filters.
Files (symfony-ux-skills)
  • references
    • api.md 12.3 KB
      Loading…
    • gotchas.md 6.5 KB
      Loading…
    • patterns.md 8.8 KB
      Loading…
  • SKILL.md 8.6 KB
    ---
    name: ux-pagination
    description: 'Symfony UX Pagination: paginate Doctrine queries, arrays and API results with numbered links or cursors. Use for filtered lists, offset, lookahead and signed cursor pagination, PaginatorInterface, ux_pagination(), twig:ux:pagination, Twig themes and ComponentWithPaginationTrait.'
    license: MIT
    metadata:
      author: Simon André
      url: https://smnandre.dev
    ---
    
    # UX Pagination
    
    One lazy, request-aware API to paginate arrays, Doctrine ORM and DBAL queries, and custom data sources. It validates `?page=` and `?cursor=`, keeps the current filters in every link, and renders accessible `<nav>` markup with real links, served as plain HTML.
    
    Since Symfony UX 3.5+. The package is **experimental**: its API may still change.
    
    ## Installation
    
    ```bash
    composer require symfony/ux-pagination
    ```
    
    Until the Flex recipe is published, register `Symfony\UX\Pagination\UXPaginationBundle::class => ['all' => true]` in `config/bundles.php`. Requires PHP 8.4+, Symfony 7.4 or 8.x, TwigBundle and Twig 3.10.3+. Doctrine ORM 3, DBAL 4.4+, TwigComponent and LiveComponent are optional.
    
    Optional stylesheet for the default theme:
    
    ```twig
    {# AssetMapper #}
    <link rel="stylesheet" href="{{ asset('@symfony/ux-pagination/style.min.css') }}">
    ```
    
    With Encore: `npm install @symfony/ux-pagination`, then `import '@symfony/ux-pagination/style.min.css';`.
    
    ## Quick Start
    
    ```php
    use Symfony\UX\Pagination\PaginatorInterface;
    
    #[Route('/products', name: 'product_index')]
    public function index(ProductRepository $repository, PaginatorInterface $paginator): Response
    {
        $products = $paginator->paginate($repository->createQueryBuilder('product'));
    
        return $this->render('product/index.html.twig', ['products' => $products]);
    }
    ```
    
    ```twig
    {% for product in products %}
        <article>{{ product.name }}</article>
    {% else %}
        <p>No product.</p>
    {% endfor %}
    
    {{ ux_pagination(products) }}
    {# or, with TwigComponent: <twig:ux:pagination :pagination="products" /> #}
    ```
    
    The page comes from the `page` route attribute, then the `page` query parameter, then defaults to 1. `paginate(page: 3)` bypasses the request. Query parameters (filters) are preserved in generated links by default.
    
    ## Choose a Strategy
    
    | The screen needs... | Strategy | Builder |
    |---------------------|----------|---------|
    | Exact total, numbered links | Offset | `query($source)` (or `paginate($source)`) |
    | Only previous/next, no count query | Lookahead | `query($source)->lookahead()` |
    | Stable traversal of a large or changing set | Cursor | `cursor($source)->orderBy([...], 'DESC')` |
    
    ```php
    // Offset with a sliding window of 5 pages
    $products = $paginator->query($qb)->perPage(20)->sliding(size: 5)->paginate();
    
    // Lookahead: fetches perPage + 1 rows, totals are null
    $activity = $paginator->query($qb)->perPage(30)->lookahead()->paginate();
    
    // Cursor: signed opaque tokens in ?cursor=, no count, no page numbers
    $entries = $paginator
        ->cursor($repository->createQueryBuilder('entry'))   // no orderBy() on the source
        ->orderBy(['createdAt', 'id'], 'DESC')               // unique tie-breaker last
        ->perPage(50)
        ->paginate();
    ```
    
    All three return iterable results; templates that only iterate and render `ux_pagination()` work with any of them. Deep offsets are rejected above `max_offset` (100,000 by default).
    
    For sort order, tie-breakers and cursor invalidation, check the [cursor pagination troubleshooting guide](references/gotchas.md#cursor-pagination).
    
    ## Builder Essentials
    
    Builders are immutable; finish with `->paginate()`:
    
    ```php
    $products = $paginator
        ->query($repository->listQuery($category))
        ->perPage(12)
        ->throwOnOutOfRange()                  // count now, 404 past the last page
        ->excludeQueryParameters('debug')      // drop a parameter from links
        ->fragment('results')                  // #results on every link
        ->paginate();
    ```
    
    - `total(int|callable)`: provide the exact total (required for `GROUP BY`, `HAVING`, multiple roots).
    - `pageParameter('orders_page')`: one parameter per list when a page shows several lists.
    - `route('name', [...])`, `path('/x')`, `queryParameters([...])`, `discardQueryString()`: control link URLs.
    - `fromCallbacks(slice: fn (int $offset, int $limit) => ..., count: fn () => ...)`: paginate an API or search engine.
    
    ## Configuration
    
    ```yaml
    # config/packages/ux_pagination.yaml
    ux_pagination:
        items_per_page: 20
        max_offset: 100000
        navigation:
            mode: sliding        # sliding | fixed | full
            size: 5
        theme: '@UXPagination/theme/default.html.twig'
        paginators:
            products:            # autowire as PaginatorInterface $productsPaginator
                items_per_page: 12
    ```
    
    Named paginators inherit the root options. Inject them by argument name (`$productsPaginator`) or with `#[Target('products')]`.
    
    ## Rendering
    
    Built-in themes: `@UXPagination/theme/default.html.twig`, `bootstrap.html.twig` (Bootstrap 5), `tailwind.html.twig`. They render numbered pages for offset results and only previous/next for lookahead and cursor results, and nothing at all when there is a single page.
    
    ```twig
    {{ ux_pagination(
        products,
        {class: 'product-pagination', 'aria-label': 'Product results'},
        theme: '@UXPagination/theme/tailwind.html.twig',
        show_info: false,
        navigation_attributes: {class: 'controls'},
        link_attributes: {class: 'link'},
    ) }}
    ```
    
    With Tailwind, add `@source "../../vendor/symfony/ux-pagination/templates";` to your CSS (Tailwind 4) or the vendor path to `content` (Tailwind 3).
    
    ## LiveComponent
    
    ```php
    use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
    use Symfony\UX\LiveComponent\Attribute\LiveProp;
    use Symfony\UX\LiveComponent\DefaultActionTrait;
    use Symfony\UX\Pagination\LiveComponent\ComponentWithPaginationTrait;
    use Symfony\UX\Pagination\PaginationBuilder;
    use Symfony\UX\Pagination\PaginatorInterface;
    
    #[AsLiveComponent]
    final class ProductList
    {
        use DefaultActionTrait;
        use ComponentWithPaginationTrait;
    
        #[LiveProp(writable: true, url: true, onUpdated: 'onQueryUpdated')]
        public string $query = '';
    
        public function __construct(
            private readonly ProductRepository $products,
            private readonly PaginatorInterface $paginator,
        ) {}
    
        protected function createPagination(): PaginationBuilder
        {
            return $this->paginator->query($this->products->searchQuery($this->query));
        }
    
        public function onQueryUpdated(): void
        {
            $this->resetPage();
        }
    }
    ```
    
    ```twig
    <div {{ attributes }}>
        <input type="search" data-model="debounce(300)|query">
        {% for product in this.pagination %}<article>{{ product.name }}</article>{% endfor %}
        {{ ux_pagination(this.pagination, link_attributes: this.paginationLinkAttributes) }}
    </div>
    ```
    
    Numbered pagination only (offset or lookahead). Links keep a real `href`, so they keep working even before LiveComponent connects.
    
    ## Key Principles
    
    **Ask what the screen promises.** Offset only when users see a total or page numbers; lookahead when "next" is enough; cursor when rows move during browsing.
    
    **Every cursor order ends with a unique field.** `['createdAt', 'id']`, one direction for all fields, no `ORDER BY` on the source query.
    
    **The page size belongs to the application.** There is no visitor-controlled per-page parameter; use `items_per_page` or `perPage()`.
    
    **Links stay links.** Turbo Frames, Turbo Drive and LiveComponent enhance them; without JavaScript, every link still works.
    
    ## References
    
    - [Symfony UX package page](https://ux.symfony.com/pagination) ([Markdown summary](https://ux.symfony.com/pagination.md)) · [`symfony/ux-pagination` on Packagist](https://packagist.org/packages/symfony/ux-pagination).
    - For strategies, application integration and deployment, see the [Symfony UX Pagination documentation](https://symfony.com/bundles/ux-pagination).
    - **API** (builders, results, Twig function, themes, translations): [references/api.md](references/api.md)
    - **Patterns** (filters, Turbo Frame, LiveComponent path routes, JSON APIs, external sources, testing): [references/patterns.md](references/patterns.md)
    - **Gotchas** (HTTP errors, cursor rules, Doctrine counts, security): [references/gotchas.md](references/gotchas.md)
    
    ### Demos
    
    - [Numbered pagination preview](https://ux.symfony.com/pagination#pagination-tour)
    - [Pagination Themes](https://ux.symfony.com/demos/pagination/themes)
    - [Cursor Pagination](https://ux.symfony.com/demos/pagination/cursor-pagination)
    - [Live Pagination with reactive filters](https://ux.symfony.com/demos/pagination/live-pagination)
    
    ## See Also
    
    - **turbo**: wrap the list and `ux_pagination()` in a `<turbo-frame>` to update only the results.
    - **live-component**: `ComponentWithPaginationTrait` for reactive filters.
    

Comments

Sign in to join the conversation.

No comments yet. Start the conversation.

Reviews (0)

No reviews yet.