3 namespace Drupal\link\Plugin\Field\FieldFormatter;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Field\FieldItemListInterface;
9 * Plugin implementation of the 'link_separate' formatter.
11 * @todo https://www.drupal.org/node/1829202 Merge into 'link' formatter once
12 * there is a #type like 'item' that can render a compound label and content
13 * outside of a form context.
16 * id = "link_separate",
17 * label = @Translation("Separate link text and URL"),
23 class LinkSeparateFormatter extends LinkFormatter {
28 public static function defaultSettings() {
33 ] + parent::defaultSettings();
39 public function viewElements(FieldItemListInterface $items, $langcode) {
41 $entity = $items->getEntity();
42 $settings = $this->getSettings();
44 foreach ($items as $delta => $item) {
45 // By default use the full URL as the link text.
46 $url = $this->buildUrl($item);
47 $link_title = $url->toString();
49 // If the link text field value is available, use it for the text.
50 if (empty($settings['url_only']) && !empty($item->title)) {
51 // Unsanitized token replacement here because the entire link title
52 // gets auto-escaped during link generation in
53 // \Drupal\Core\Utility\LinkGenerator::generate().
54 $link_title = \Drupal::token()->replace($item->title, [$entity->getEntityTypeId() => $entity], ['clear' => TRUE]);
57 // The link_separate formatter has two titles; the link text (as in the
58 // field values) and the URL itself. If there is no link text value,
59 // $link_title defaults to the URL, so it needs to be unset.
60 // The URL version may need to be trimmed as well.
61 if (empty($item->title)) {
64 $url_title = $url->toString();
65 if (!empty($settings['trim_length'])) {
66 $link_title = Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE);
67 $url_title = Unicode::truncate($url_title, $settings['trim_length'], FALSE, TRUE);
71 '#theme' => 'link_formatter_link_separate',
72 '#title' => $link_title,
73 '#url_title' => $url_title,
77 if (!empty($item->_attributes)) {
78 // Set our RDFa attributes on the <a> element that is being built.
79 $url->setOption('attributes', $item->_attributes);
81 // Unset field item attributes since they have been included in the
82 // formatter output and should not be rendered in the field template.
83 unset($item->_attributes);