---
title: "Views"
package: "Pagerfanta"
version: "5.x"
canonical_url: "https://www.babdev.com/open-source/packages/pagerfanta/docs/5.x/views"
package_supported: true
version_released: false
notice:
  - "Version 5.x of Pagerfanta has not been released yet. Its API may change before release."
---
# Views

Pagerfanta defines `Pagerfanta\View\ViewInterface` which is the abstraction layer for rendering a pagination list.

The interface requires three methods to be implemented:

- `render`: Generates the markup for the pagination list
- `supports`: Checks whether the view can render a pager
- `getName`: Retrieves the unique name of the view

```php
<?php

namespace Pagerfanta\View;

use Pagerfanta\PagerInterface;
use Pagerfanta\RouteGenerator\PositionRouteGeneratorInterface;

interface ViewInterface
{
    /**
     * @throws \Pagerfanta\Exception\InvalidArgumentException if the pager is not supported by this view
     */
    public function render(PagerInterface $pager, PositionRouteGeneratorInterface $routeGenerator, array $options = []): string;

    public function supports(PagerInterface $pager): bool;

    public function getName(): string;
}
```

Views are given a [route generator](/open-source/packages/pagerfanta/docs/5.x/route-generator) to build the URL for each page they link to.

## Base Classes

Pagerfanta provides two base classes to build upon to assist in creating custom views.

### `Pagerfanta\View\View`

The `View` class is the base class that is recommended for use when rendering numbered page links. It contains all of the logic necessary for calculating the page items to be displayed in the pagination list, and supports any offset pager (a pager implementing `Pagerfanta\OffsetPagerInterface`, such as the `Pagerfanta\Pagerfanta` class).

### `Pagerfanta\View\TemplateView`

The `TemplateView` class is an extension of the `View` class and provides support for rendering pagination lists using `Pagerfanta\View\Template\TemplateInterface` instances.

## Available Views

Below is a list of the views that are available with this package, and the corresponding template class. These views render numbered page links for offset pagers.

| View Name            | View Class Name                         | Template Class Name                                  |
|----------------------|-----------------------------------------|------------------------------------------------------|
| `default`            | `Pagerfanta\View\DefaultView`           | `Pagerfanta\View\Template\DefaultTemplate`           |
| `foundation6`        | `Pagerfanta\View\Foundation6View`       | `Pagerfanta\View\Template\Foundation6Template`       |
| `semantic_ui`        | `Pagerfanta\View\SemanticUiView`        | `Pagerfanta\View\Template\SemanticUiTemplate`        |
| `twitter_bootstrap`  | `Pagerfanta\View\TwitterBootstrapView`  | `Pagerfanta\View\Template\TwitterBootstrapTemplate`  |
| `twitter_bootstrap3` | `Pagerfanta\View\TwitterBootstrap3View` | `Pagerfanta\View\Template\TwitterBootstrap3Template` |
| `twitter_bootstrap4` | `Pagerfanta\View\TwitterBootstrap4View` | `Pagerfanta\View\Template\TwitterBootstrap4Template` |
| `twitter_bootstrap5` | `Pagerfanta\View\TwitterBootstrap5View` | `Pagerfanta\View\Template\TwitterBootstrap5Template` |

## Sequential Views

The views above render numbered page links, which requires the total number of pages and is only possible with offset pagers. Sequential views only render links to the previous and next pages, so they can render any pager, including [cursor pagers](/open-source/packages/pagerfanta/docs/5.x/cursor-pagination).

The `Pagerfanta\View\SequentialView` renders the previous and next links using any template implementing `Pagerfanta\View\Template\SequentialTemplateInterface`, which all of the templates listed above do. The view name defaults to `sequential` and can be changed with the second argument.

```php
<?php

use Pagerfanta\View\SequentialView;
use Pagerfanta\View\Template\TwitterBootstrap5Template;

$view = new SequentialView(new TwitterBootstrap5Template(), 'twitter_bootstrap5_sequential');

echo $view->render($pager, $routeGenerator, ['prev_message' => 'Newer', 'next_message' => 'Older']);
```

The previous link is disabled when there is no previous page, and omitted entirely for cursor pagers which do not support backward navigation.

Use the `supports` method to check whether a view can render a pager.

```php
<?php

use Pagerfanta\View\DefaultView;
use Pagerfanta\View\SequentialView;
use Pagerfanta\View\Template\DefaultTemplate;

$numberedView = new DefaultView();
$sequentialView = new SequentialView(new DefaultTemplate());

$view = $numberedView->supports($pager) ? $numberedView : $sequentialView;

echo $view->render($pager, $routeGenerator);
```

## Twig View

Pagerfanta includes native support for the [Twig](https://twig.symfony.com/) templating engine and allows integrators to build flexible templates for rendering their pagers.

If you have not already, you will need to install the `pagerfanta/twig` package to use the Twig integration.

The below table lists the available templates and the CSS framework they correspond to.

| Template Name                              | Framework                                                     |
|--------------------------------------------|---------------------------------------------------------------|
| `@Pagerfanta/default.html.twig`            | None (Pagerfanta's default view)                              |
| `@Pagerfanta/foundation6.html.twig`        | [Foundation](https://get.foundation/index.html) (version 6.x) |
| `@Pagerfanta/semantic_ui.html.twig`        | [Semantic UI](https://semantic-ui.com) (version 2.x)          |
| `@Pagerfanta/tailwind.html.twig`           | [Tailwind CSS](https://tailwindcss.com/)                      |
| `@Pagerfanta/twitter_bootstrap.html.twig`  | [Bootstrap](https://getbootstrap.com) (version 2.x)           |
| `@Pagerfanta/twitter_bootstrap3.html.twig` | [Bootstrap](https://getbootstrap.com) (version 3.x)           |
| `@Pagerfanta/twitter_bootstrap4.html.twig` | [Bootstrap](https://getbootstrap.com) (version 4.x)           |
| `@Pagerfanta/twitter_bootstrap5.html.twig` | [Bootstrap](https://getbootstrap.com) (version 5.x)           |

### Configuring the Twig Integration

In order to use the Twig integration, you will need to register the Twig extension, a runtime loader to resolve the runtime service, and the Pagerfanta template path to your Twig environment.

```php
<?php

use Pagerfanta\Twig\Extension\PagerfantaExtension;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\RuntimeLoader\ContainerRuntimeLoader;

/*
 * We'll use Reflection to dynamically resolve the path to the templates provided by the package.
 * This method will work regardless of whether the monolithic `pagerfanta/pagerfanta` package
 * or the `pagerfanta/twig` package is installed.
 */
$refl = new \ReflectionClass(PagerfantaExtension::class);
$path = \dirname($refl->getFileName(), 2) . '/templates';

$loader = new FilesystemLoader(['/path/to/app/templates']);

// The namespace *MUST* be "Pagerfanta" otherwise the templates will not work correctly
$loader->addPath($path, 'Pagerfanta');

$environment = new Environment($loader);

/*
 * Add the runtime loader so the runtime serivce can be lazy loaded.
 *
 * If using the PSR-11 runtime loader, the runtime service must
 * be registered to the container using its FQCN as its service ID,
 * i.e. `Pagerfanta\Twig\Extension\PagerfantaRuntime`
 */
/** @var Psr\Container\ContainerInterface $container */
$environment->addRuntimeLoader(new ContainerRuntimeLoader($container));

// Add the extension
$environment->addExtension(new PagerfantaExtension());
```

### Rendering Cursor Pagers

The Twig view supports every pager. Offset pagers are rendered with numbered page links, and all other pagers (such as cursor pagers) are rendered with previous and next links using the same templates. To render an offset pager with only previous and next links, set the `sequential` option.

```twig
{{ pagerfanta(pager, 'twig', {'sequential': true}) }}
```

When the view given to the `pagerfanta()` function (or the default view) cannot render a pager, such as a cursor pager with a numbered view, an exception is thrown. To render these pagers with another view instead, give the name of a default sequential view as the fourth argument of the `Pagerfanta\Twig\Extension\PagerfantaRuntime` constructor. A view explicitly named in the `pagerfanta()` function never falls back to the default sequential view.

The `pagerfanta_position_url()` function generates the URL for a position, such as the next page of a pager.

```twig
{% if pager.hasNextPage() %}
    <a href="{{ pagerfanta_position_url(pager.nextPosition) }}">Load more</a>
{% endif %}
```

The [route generator factory](/open-source/packages/pagerfanta/docs/5.x/route-generator#generator-factory) given to the runtime is used to create the route generators for the views and for the `pagerfanta_page_url()` and `pagerfanta_position_url()` functions.

#### Encoding Cursors

The `pagerfanta_encode_cursor()` function encodes a `Pagerfanta\Position\CursorPosition` or `Pagerfanta\Cursor\Cursor` to a string, for when a cursor needs to be passed to something other than a URL, such as a JavaScript library or a form field.

```twig
{% if pager.hasNextPage() %}
    <button type="button" data-cursor="{{ pagerfanta_encode_cursor(pager.nextPosition) }}">Load more</button>
{% endif %}
```

The cursors are encoded with the `Pagerfanta\Cursor\CursorEncoderInterface` given to the `Pagerfanta\Twig\Extension\PagerfantaRuntime` constructor, which defaults to the `Pagerfanta\Cursor\Base64JsonCursorEncoder`.

### Creating a Twig View Template

If creating a custom template, you are encouraged to extend the `@Pagerfanta/default.html.twig` template and override only the blocks needed.

Generally, the `pager_widget` block should only be extended if you need to change the wrapping HTML for the paginator. The `pager` block should still be rendered from your extended block.

The `pager` block is designed to hold the structure of the pager and generally should not be extended unless the intent is to change the logic involved in rendering the paginator (such as removing the ellipsis separators or changing to only display previous/next buttons).

When rendering a Twig view, the following options are passed into the template for use. Note that for the most part, only the `pager` block will use these variables.

- `pagerfanta` - The pager, a `Pagerfanta\OffsetPagerInterface` object when rendering numbered page links
- `route_generator` - A `Pagerfanta\RouteGenerator\PageNumberRouteGenerator` object, whose `route()` method generates the URL for a page number using the route generator created by the `pagerfanta()` Twig function
- `options` - The options array passed through the `pagerfanta()` Twig function
- `start_page` - The calculated start page for the list of items displayed between separators, this is based on the `proximity` option and the total number of pages
- `end_page` - The calculated end page for the list of items displayed between separators, this is based on the `proximity` option and the total number of pages
- `current_page` - The current page in the paginated list
- `nb_pages` - The total number of pages in the paginated list
- `sequential` - Whether the pager is rendered with only previous and next links

When rendering with only previous and next links, the `sequential_pager` block is rendered instead of the numbered page links, and the page number variables are not available. Instead, the following variables are passed into the template:

- `route_generator` - A `Pagerfanta\RouteGenerator\PositionRouteGeneratorDecorator` object, whose `route()` method generates the URL for a position
- `supports_backward_navigation` - Whether the pager supports backward navigation, the previous link is omitted when it does not
- `previous_position` - The position of the previous page, or null if there is no previous page
- `next_position` - The position of the next page, or null if there is no next page

<div class="docs-note">The dispatch to the <code>sequential_pager</code> block is part of the <code>pager</code> block. If your template overrides the <code>pager</code> block, render the <code>sequential_pager</code> block from it when the <code>sequential</code> variable is true to support cursor pagers. Templates which only override the markup blocks (such as <code>pager_widget</code>, <code>previous_page_link</code>, and <code>next_page_link</code>) support cursor pagers without any changes.</div>

Additionally, for most page blocks (`previous_page_link`, `page_link`, `current_page_link`, and `next_page_link`), there are two additional variables available:

- `page` - The current page in the pager
- `path` - The generated URL for the item

If you want to create your own Twig template, the quickest and easiest way to do that is to extend one of the supplied templates (typically the default one). Have a look at `semantic_ui.html.twig` to see the blocks you will likely want to override.

The `previous_page_message` and `next_page_message` blocks, which render the labels of the previous and next links, are defined by the `@Pagerfanta/messages.html.twig` template instead of the `@Pagerfanta/default.html.twig` template. The Twig view always composes the messages template after every other template, so these blocks can be overridden by any template being rendered. As the messages are not part of the template's inheritance chain, an override of these blocks cannot call the `parent()` function.

### Composing Templates

The `template` option (and the default template given to the `Pagerfanta\Twig\View\TwigView` constructor) also accepts a list of template names, ordered from highest to lowest precedence. The blocks of these templates are composed together, so a template only needs to define the blocks it overrides and does not need to extend another template. This allows a set of overrides to be reused across any of the supplied templates.

For example, a `pager_messages.html.twig` template containing only the `previous_page_message` and `next_page_message` blocks can be combined with the Bootstrap 5 template:

```twig
{{ pagerfanta(pager, 'twig', {'template': ['pager_messages.html.twig', '@Pagerfanta/twitter_bootstrap5.html.twig']}) }}
```

The default template given to the `Pagerfanta\Twig\View\TwigView` constructor, the `@Pagerfanta/default.html.twig` template, and the `@Pagerfanta/messages.html.twig` template are always appended to the template from the `template` option (whether it is a single template or a list), so any block not defined by the given templates falls back to them. If a template appears more than once, only its highest precedence position is used.

As each template is composed with the templates it extends before the next template in the list, a block defined by a template extending one of the supplied templates takes precedence over the same block in a later template. Because the supplied templates do not define the message blocks, the default template given to the constructor can provide the messages for every template, such as to translate them:

```php
<?php

use Pagerfanta\Twig\View\TwigView;

$view = new TwigView($twig, ['@Pagerfanta/default.html.twig', 'pager_messages.html.twig']);
```

```twig
{# Rendered with the Bootstrap 5 markup and the messages from pager_messages.html.twig #}
{{ pagerfanta(pager, 'twig', {'template': '@Pagerfanta/twitter_bootstrap5.html.twig'}) }}
```

### Link Attributes

All of the supplied templates render the `link_attributes` block at the end of the opening tag of each link, which renders nothing by default. Override this block to add attributes to the links without having to override the markup of each link.

The block is rendered with the variables of the link being rendered:

- `relation` - The relation of the link to the current page: `previous`, `page`, or `next` (the first, last, and numbered page links use `page`)
- `page` - The page number the link points to, or null for links to a cursor position
- `position` - The `Pagerfanta\Position\Position` the link points to when rendering with only previous and next links, or null when rendering numbered page links
- `path` - The generated URL for the link

The rendered attributes must start with a space. For example, a `pager_link_attributes.html.twig` template can be combined with any of the supplied templates with a [list of templates](#composing-templates):

```twig
{%- block link_attributes %} data-relation="{{ relation }}"{% if page is not null %} data-page="{{ page }}"{% endif %}{% endblock link_attributes -%}
```

```twig
{{ pagerfanta(pager, 'twig', {'template': ['pager_link_attributes.html.twig', '@Pagerfanta/twitter_bootstrap5.html.twig']}) }}
```

The block can also be overridden in a template extending one of the supplied templates.

```twig
{%- extends '@Pagerfanta/twitter_bootstrap5.html.twig' -%}

{%- block link_attributes %} data-relation="{{ relation }}"{% if page is not null %} data-page="{{ page }}"{% endif %}{% endblock link_attributes -%}
```

<div class="docs-note">Always quote the attribute values so they are escaped by Twig's autoescaping, and do not build attribute names from user input. The <code>href</code>, <code>rel</code>, and <code>class</code> attributes are rendered by the link markup blocks and should not be added with the <code>link_attributes</code> block. If your template overrides a link markup block (such as <code>page_link</code>), render the <code>link_attributes</code> block in its opening tag to support link attributes.</div>

## Reusable View Configurations

Sometimes you want to reuse options for a view in your project and you don't want to repeat those options each time you render a view, or you have different configurations for a view and you want to save those configurations to be able to change them easily.

For this you can define views with the `Pagerfanta\View\OptionableView` class, which is a decorator for any `Pagerfanta\View\ViewInterface` instance.

```php
<?php

use Pagerfanta\View\DefaultView;
use Pagerfanta\View\OptionableView;

$defaultView = new DefaultView();

$myView1 = new OptionableView($defaultView, ['proximity' => 5]);
$myView2 = new OptionableView($defaultView, ['proximity' => 2, 'prev_message' => 'Anterior', 'next_message' => 'Siguiente']);

$myView1->render($pagerfanta, $routeGenerator);

// Overwriting the optionable view options
$myView2->render($pagerfanta, $routeGenerator, ['next_message' => 'Siguiente!!']);
```
