Drupal link function

The Drupal link function is a handy and easy way to create hyperlinks in your module or theme.

The syntax for the link function is:

  1. print l(<em>anchor text</em>, <em>path</em>);

This is an example of a simple link that might exist in a theme template file:

  1. print l('See full post', 'node/'.$node->nid);

The above example would create the following hyper link (assuming that the given $node->nid is 1):

  1. <a href="node/1">See full post</a>

Attributes

You can easily add attributes to the link.
For example, lets say you want to add a class to your anchor link called "see-more" and
you want to add target="_blank"

Drupal 5:

  1. $attributes = array( 'class' => 'see-more', 'target' => '_blank' );
  2. print l('See full post', 'node/'.$node->nid, $attributes);

Drupal 6:

  1.  
  2. $options['attributes'] = array( 'class' => 'see-more', 'target' => '_blank' );
  3. print l('See full post', 'node/'.$node->nid, $options);

The above examples would create the following hyper link:

  1. <a href="node/1" class="see-more" target="_blank">See full post</a>

External links

If the link is external, then use the full URL including the http://.
For example:

  1. print l('Google', 'http://www.google.com');

This would create:

  1. <a href="http://www.google.com">Google</a>

Why bother?

It is generally easier to create a hyper link using the link l() function that typing out the full html for an anchor link.
Using the link function is more secure because check_plain and check_url will run automatically, which helps prevent xss attacks.
And finally, active classes are automatically assigned when using the link function.

For more information, see the Drupal API page on the Drupal link function

If you liked this, you'll love my book, Master Drupal Module Development.

"..the must have drupal developers book"


Feeling stuck with Drupal 8 module dev?

Get the free 7 lesson course that will help you get started today without feeling overwhelmed.

  • Create Drupal modules with just a few commands using the Drupal Console
  • Create custom pages
  • Create custom blocks
  • Create admin forms
  • Demystify routers and controllers
  • Bonus material

Find out more


Comments

What I do to call function with a link?

Instead:
print l('See full post', 'node/'.$node->nid, $options);

I want 'mymodule/' not 'node/' but in my site not work!

Thanks

Hi Blair,
I had a bug that broke the regulae href ... link because of a filter in ckeditor.
find it very usefull ...THX !!
Rami

I am a beginner in Drupal and I have found this web site very useful for me to learn Drupal. I have come here very frequently during the last few days and have learned a lot. Thank you so much

Add new comment