You are here

function views_tokens in Views (for Drupal 7) 8.3

Same name and namespace in other branches
  1. 7.3 views.tokens.inc \views_tokens()

Implements hook_tokens().

File

./views.tokens.inc, line 69
Token integration for the views module.

Code

function views_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $url_options = array(
    'absolute' => TRUE,
  );
  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
  }
  $sanitize = !empty($options['sanitize']);
  $langcode = isset($options['language']) ? $options['language']->langcode : NULL;
  $replacements = array();
  if ($type == 'view' && !empty($data['view'])) {
    $view = $data['view'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'name':
          $replacements[$original] = $sanitize ? check_plain($view->storage
            ->getHumanName()) : $view->storage
            ->getHumanName();
          break;
        case 'description':
          $replacements[$original] = $sanitize ? check_plain($view->storage->description) : $view->storage->description;
          break;
        case 'machine-name':
          $replacements[$original] = $view->storage->name;
          break;
        case 'title':
          $title = $view
            ->getTitle();
          $replacements[$original] = $sanitize ? check_plain($title) : $title;
          break;
        case 'url':
          if ($path = $view
            ->getUrl()) {
            $replacements[$original] = url($path, $url_options);
          }
          break;
        case 'base-table':
          $replacements[$original] = $view->storage->base_table;
          break;
        case 'base-field':
          $replacements[$original] = $view->storage->base_field;
          break;
        case 'total-rows':
          $replacements[$original] = count($view->result);
          break;
        case 'items-per-page':
          $replacements[$original] = (int) $view
            ->getItemsPerPage();
          break;
        case 'current-page':
          $replacements[$original] = (int) $view
            ->getCurrentPage() + 1;
          break;
        case 'page-count':

          // If there are no items per page, set this to 1 for the division.
          $per_page = $view
            ->getItemsPerPage() ?: 1;
          $replacements[$original] = (int) ceil(count($view->result) / $per_page);
          break;
      }
    }

    // [view:url:*] nested tokens. This only works if Token module is installed.
    if ($url_tokens = token_find_with_prefix($tokens, 'url')) {
      if ($path = $view
        ->getUrl()) {
        $replacements += token_generate('url', $url_tokens, array(
          'path' => $path,
        ), $options);
      }
    }
  }
  return $replacements;
}