Inspired by Link field title from entity/route, I created a preprocess function.
/**
* Prepares variables for link fields.
*/
function mytheme_preprocess_field__node__field_links(&$variables) {
/* If it's an internal link and there was no link title provided by the editor,
then use the entity label as the link text.*/
$i = 0;
foreach ($variables['element']['#items'] as &$item) {
if($item->getUrl()->isRouted()) {
$parameters = $item->getUrl()->getRouteParameters();
if (!empty($parameters)) {
foreach ($parameters as $entity_type => $id) {
if ($entity = Drupal::entityTypeManager()
->getStorage($entity_type)
->load($id)) {
$variables['items'][$i]['content']['#url_title'] = Link::fromTextAndUrl($entity->label(), $entity->toURL())
->toString();
break;
}
}
}
}
$i++;
}
}