[Drupal] How to create an external anchor tag using l() function?

| | 1 min read

l() function is a beautiful thing available in Drupal. It is a simple and secure way to create an HTML anchor tag. Usually we think of l() function to format an internal anchor tag which supports things like clean URLs. You can still create an external URL link with the l() function as an anchor tag.

For this, just follow these steps:

1. Specify whether external Anchor Tag

<?php
  l(t('Link Text'), 'http://external-url.com', array('external' => TRUE,));
?>

2. Specify Anchor Tag Attributes

If it is an external link, obiviously we would want this to open in a new tab. We can specify this using a common anchor tag attribute 'target'. Here's how we can modify our previous example to add this:

<?php 
  print l(t('Link Text'), 'http://external-url.com', array(
    'external' => TRUE,
    'attributes' => array(
      'target'=> '_blank',
      'title' => 'Title Text',
    ),
  ));
?>

The output will be:

<a title="Title Text" target="_blank" href="http://external-url.com">Link Text</a>