In Drupal 7, one could do the following one line::
t('Visit !mylink', ['!mylink' => l('my website', 'http://example.com')]);
But that no longer works in Drupal 8 or 9 😞. So far, I've tried this:
First I create a link, Drupal 8 style:
$mylink = Link::fromTextAndUrl('my website', Url::fromUri('http://example.com'));
Then try to create a string that can be printed. I've tried toString()
:
t('Visit @mylink', ['@mylink' => $mylink->toString()]);
However, we're not supposed to do this. The API docs says:
Do not use this method to render a link in an HTML context. In an HTML context, self::toRenderable() should be used so that render cache information is maintained.
So I try to use toRenderable()
:
t('Visit @mylink', ['@mylink' => render($mylink->toRenderable()]);
But PHP 7.2 doesn't like it. The call to t()
produces the following Notice:
Notice: Only variables should be passed by reference ...
Fair enough - but how is this done?
I could not find how to do this described in any of the obvious docs, such as:
- https://www.drupal.org/docs/security-in-drupal/sanitizing-output
- https://www.drupal.org/docs/security-in-drupal/writing-secure-code-for-drupal
So my question is:
What is the best practice for writing a link to the screen in Drupal 8?
(Environment: Ubuntu 20.04 LTS, Drupal 8.8.6 (core + devel), procedural code - e.g. hook_help()
).