public function ReadmoreFormatter::viewElements in Readmore 8
Same name and namespace in other branches
- 2.x src/Plugin/Field/FieldFormatter/ReadmoreFormatter.php \Drupal\readmore\Plugin\Field\FieldFormatter\ReadmoreFormatter::viewElements()
Builds a renderable array for a field value.
Parameters
\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.
string $langcode: The language that should be used to render the field.
Return value
array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.
Overrides FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ ReadmoreFormatter.php, line 151 - Contains \Drupal\readmore\Plugin\field\FieldFormatter\ReadmoreFormatter.
Class
- ReadmoreFormatter
- Plugin implementation of the 'readmore' formatter.
Namespace
Drupal\readmore\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$settings = $this
->getSettings();
$current_path = \Drupal::service('path.current')
->getPath();
$url_object = \Drupal::service('path.validator')
->getUrlIfValid($current_path);
$route_name = $url_object
->getRouteName();
$route_parameters = $url_object
->getRouteParameters();
$current_url = Url::fromRoute($route_name, $route_parameters, [
'absolute' => TRUE,
]);
$read_less = $this
->t('Read less');
$read_more = $this
->t('Read more');
// Prepare readless link.
$link_less = Link::fromTextAndUrl($read_less, $current_url);
$link_less = $link_less
->toRenderable();
$link_less['#attributes']['class'][] = 'readless-link';
// Prepare readmore link.
$link_more = Link::fromTextAndUrl($read_more, $current_url);
$link_more = $link_more
->toRenderable();
$link_more['#attributes']['class'][] = 'readmore-link';
foreach ($items as $delta => $item) {
$text = $item->value;
$text_length = Unicode::strlen($text);
$trim_length = $settings['trim_length'];
// Don't do anything if text length less than defined.
if ($text_length > $trim_length) {
// Add Read less if need.
if ($settings['show_readless']) {
$text .= ' ' . render($link_less);
}
// Get trimmed string.
$summary = readmore_truncate_string($text, isset($item->format) ? $item->format : NULL, $trim_length, $settings['wordsafe'], $settings['trim_on_break']);
// Add readmore link.
$summary .= '<span>';
$summary .= $settings['ellipsis'] ? $this
->t('...') : NULL;
if ($settings['show_readmore']) {
$summary .= render($link_more);
}
$summary .= '</span>';
// Close all HTML tags.
$summary = Html::normalize($summary);
$elements[$delta] = [
'#theme' => 'readmore',
'#summary' => Markup::create($summary),
'#text' => Markup::create($text),
];
}
else {
$elements[$delta] = [
'#markup' => $text,
];
}
}
$elements['#attached']['library'][] = 'readmore/readmore';
return $elements;
}