5

I have a hard time to style a link via the Drupal 8 render structure. This link needs to be displayed in my custom module:

$add_link = \Drupal::l('<i class="fa fa-cog"></i>' . t('Add new project'), $url);

So between de tags I want a Font awesome icon in front of the text. But Drupal print all html out as readable text.

I also notice that the l() function is deprecated in Drupal 8. So what is the best way to do this in the Drupal 8 render structure?

user3411864
  • 624
  • 2
  • 12
  • 27

3 Answers3

7

If, like me, you wanted to use a render array of #type => 'link' and include an icon with it then you can do the following:

<?php
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;

$form['actions']['reset_password'] = [
  '#type' => 'link',
  '#title' => Markup::create('<span class="glyphicon glyphicon-cog"></span> Forgot / Reset Password'),
  '#url' => Url::fromRoute('user.pass'),
];
joshmiller
  • 251
  • 3
  • 5
2

Took me a while, but this should work. Your code has a $url variable which may work fine, but this code below also shows how i got my $url.

$url = new Url(
  'entity.eab_contact_entity.edit_form', array(
    'eab_contact_entity' => $entity->id(),
  )
);
$icon_text = $this->t('<i class="fa fa-pencil"></i>');
$edit_link = \Drupal::service('link_generator')->generate($icon_text, $url);

It turns out that any text that goes into a link needs to be 'safe', so that malicious code cannot be injected etc. If you're curious, it was discussed at length here: https://www.drupal.org/node/2273923

The main point, though, and what makes the above code work for me and answers your question, is the $this->t() surrounding the font-awesome string '<i class="fa fa-pencil"></i>'. That renders it 'safe' and the link generated has the HTML we want, rather than just printing out the text of the HTML.

Finally, in case you are looking for help generating your URL, this tutorial has a lot of hints.

marqpdx
  • 51
  • 1
  • 4
0

Or if you need to pass spectial chars like &shy; or any HTML tag in your link title you can also use the following:

$link_text = Markup::create('<div>' . $node->getTitle() . '</div>');
$link = Link::fromTextAndUrl($link_text, $node->toUrl());