跳转到主要内容

主页内容

Drupal文章内容页中实现“上一篇”、“下一篇”

由 webadmin 发布于 阅读 65 次

在主题下的.theme文件中添加如下代码:

use Drupal\node\NodeInterface;
/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_node(&$variables) {
  if ($variables['node'] instanceof NodeInterface) {
    $node = $variables['node'];
    $prev = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->getQuery('AND')
      ->accessCheck(false)
      ->condition('nid', $node->id(), '<')
      ->condition('type', $node->getType())
      ->sort('nid', 'DESC')
      ->range(0, 1)
      ->execute();
    if ($prev) {
      $prev_nid = array_shift($prev);
      $prev_node = \Drupal\node\Entity\Node::load($prev_nid);
      $variables['prev'] = [
        'nid' => $prev_nid,
        'title' => $prev_node->getTitle(),
      ];
    }
    else {
      $variables['prev'] = NULL;
    }
    $next = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->getQuery('AND')
      ->accessCheck(false)
      ->condition('nid', $node->id(), '>')
      ->condition('type', $node->getType())
      ->sort('nid', 'ASC')
      ->range(0, 1)
      ->execute();
    if ($next) {
      $next_nid = array_shift($next);
      $next_node = \Drupal\node\Entity\Node::load($next_nid);
      $variables['next'] = [
        'nid' => $next_nid,
        'title' => $next_node->getTitle(),
      ];
    }
    else {
      $variables['next'] = NULL;
    }
  }
}

在内容页模板(例如:node--full.html.twig)中使用如下代码调用:

{% if prev is not empty and prev.nid is not empty %}
    上一篇:
    <a href="{{ path('entity.node.canonical', {'node': prev.nid}) }}">
      {{ prev.title }}
    </a>
{% endif %}
{% if next is not empty and next.nid is not empty %}
    下一篇:
    <a href="{{ path('entity.node.canonical', {'node': next.nid}) }}">
      {{ next.title }}
    </a>
{% endif %}