Drupal - use l or url function for mailto links
Asked Answered
M

5

13

Does anyone know how to use the l() or url() function to create mailto links?

I am running drupal 6.

Madiemadigan answered 22/9, 2009 at 13:26 Comment(0)
U
37

You need to use the absolute option:

l('Mail me', 'mailto:[email protected]', array('absolute' => TRUE));

will generate

<a href="mailto:[email protected]">Mail Me</a>
Ununa answered 22/9, 2009 at 14:31 Comment(1)
You may want to add quotes around 'absolute'. Just for people out there learning PHP...Lusterware
A
2

A good practice is to use the t() function with strings. Code should be then:

l(t('Mail me'), 'mailto:[email protected]', array('absolute' => TRUE));
Alexandrina answered 29/10, 2015 at 16:42 Comment(0)
L
2

Drupal 9+ solution

Drupal core has this code in Drupal\Core\Field\Plugin\Field\FieldFormatter\MailToFormatter:

      $elements[$delta] = [
        '#type' => 'link',
        '#title' => $item->value,
        '#url' => Url::fromUri('mailto:' . $item->value),
      ];

So you can create a render array like so:

[
  '#type' => 'link',
  '#title' => $email,
  '#url' => Url::fromUri('mailto:' . $email),
];

Or like this:

Link::fromTextAndUrl($email, Url::fromUri('mailto:' . $email))->toRenderable();
Lesleylesli answered 15/7, 2022 at 14:36 Comment(0)
E
0

Preferably none:

l() is useful for the output of internal links:

it handles aliased paths and adds an 'active' class attribute to links that point to the current page (for theming)" see reference

You need none of the above. Same goes for url(). You CAN use them, but why not keeping it simple and just use the HTML anchor tag directly.

Ex answered 30/10, 2015 at 3:51 Comment(0)
W
0

In Drupal 9 I found no other solution than:

$this->t('<a href="@link">This is a mail link</a>', ['@link' => 'mailto:[email protected]']);
While answered 21/4, 2021 at 19:5 Comment(1)
Please explain what your code does and how it does it.Facer

© 2022 - 2024 — McMap. All rights reserved.