Skip to content

Instantly share code, notes, and snippets.

@Niklan
Last active August 8, 2022 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Niklan/b05389d431da09fbae6b98921f9c6b4d to your computer and use it in GitHub Desktop.
Save Niklan/b05389d431da09fbae6b98921f9c6b4d to your computer and use it in GitHub Desktop.
Previous - next links for Drupal 8
{% if next or previous %}
<div class="previous-next">
<div class="previous-next__previous">
{% if previous %}
<a href="{{ previous.url }}" class="previous-next__link previous-next__link--previous">
<span>← {{ 'Previous post'|t }}</span>
{{ previous.label }}
</a>
{% endif %}
</div>
<div class="previous-next__next">
{% if next %}
<a href="{{ next.url }}" class="previous-next__link previous-next__link--next">
<span>{{ 'Next post'|t }} →</span>
{{ next.label }}
</a>
{% endif %}
</div>
</div>
{% endif %}
/**
* Implements hook_theme().
*/
function niklan_theme($existing, $type, $theme, $path) {
$file = 'MYMODULE.theme.inc';
return [
'MYMODULE_previous_next' => [
'variables' => [
'entity' => NULL,
],
'file' => $file,
],
];
}
/**
* Implements template_preprocess_HOOK().
*/
function template_preprocess_MYMODULE_previous_next(&$variables) {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $variables['entity'];
$variables['next'] = [];
$variables['previous'] = [];
$next_entity_id = \Drupal::entityQuery($entity->getEntityTypeId())
->condition('type', $entity->bundle())
->condition('created', $entity->getCreatedTime(), '>')
->range(0, 1)
->sort('created', 'ASC')
->execute();
if (!empty($next_entity_id)) {
$next_entity = \Drupal::entityTypeManager()
->getStorage($entity->getEntityTypeId())
->load(reset($next_entity_id));
$variables['next']['label'] = $next_entity->label();
$variables['next']['url'] = $next_entity->toUrl()->toString(TRUE)->getGeneratedUrl();
}
$previous_entity_id = \Drupal::entityQuery($entity->getEntityTypeId())
->condition('type', $entity->bundle())
->condition('created', $entity->getCreatedTime(), '<')
->range(0, 1)
->sort('created', 'DESC')
->execute();
if (!empty($previous_entity_id)) {
$previous_entity = \Drupal::entityTypeManager()
->getStorage($entity->getEntityTypeId())
->load(reset($previous_entity_id));
$variables['previous']['label'] = $previous_entity->label();
$variables['previous']['url'] = $previous_entity->toUrl()->toString(TRUE)->getGeneratedUrl();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment