Community Documentation

l

5 common.inc l($text, $path, $attributes = array(), $query = NULL, $fragment = NULL, $absolute = FALSE, $html = FALSE)
6 common.inc l($text, $path, $options = array())
7 common.inc l($text, $path, array $options = array())
8 common.inc l($text, $path, array $options = array())

Formats an internal or external URL link as an HTML anchor tag.

This function correctly handles aliased paths, and adds an 'active' class attribute to links that point to the current page (for theming), so all internal links output by modules should be generated by this function if possible.

Parameters

$text: The link text for the anchor tag.

$path: The internal path or external URL being linked to, such as "node/34" or "http://example.com/foo". After the url() function is called to construct the URL from $path and $options, the resulting URL is passed through check_url() before it is inserted into the HTML anchor tag, to ensure well-formed HTML. See url() for more information and notes.

$options: An associative array of additional options, with the following elements:

  • 'attributes': An associative array of HTML attributes to apply to the anchor tag.
  • 'html' (default FALSE): Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag.
  • 'language': An optional language object. If the path being linked to is internal to the site, $options['language'] is used to look up the alias for the URL, and to determine whether the link is "active", or pointing to the current page (the language as well as the path must match).This element is also used by url().
  • Additional $options elements used by the url() function.

Return value

An HTML string containing a link to the given path.

▾ 113 functions call l()

actions_synchronize in includes/actions.inc
Synchronize actions that are provided by modules.
aggregator_form_category_submit in modules/aggregator/aggregator.admin.inc
Process aggregator_form_category form submissions.
aggregator_form_feed_submit in modules/aggregator/aggregator.admin.inc
Process aggregator_form_feed form submissions.
aggregator_view in modules/aggregator/aggregator.admin.inc
Displays the aggregator administration page.
block_admin_display_form in modules/block/block.admin.inc
Generate main blocks administration form.
blogapi_blogger_edit_post in modules/blogapi/blogapi.module
Blogging API callback. Modifies the specified blog node.
blogapi_blogger_new_post in modules/blogapi/blogapi.module
Blogging API callback. Inserts a new blog post as a node.
blog_form in modules/blog/blog.module
Implementation of hook_form().
blog_page_last in modules/blog/blog.pages.inc
Menu callback; displays a Drupal page containing recent blog entries of all users.
blog_page_user in modules/blog/blog.pages.inc
Menu callback; displays a Drupal page containing recent blog entries of a given user.
blog_user in modules/blog/blog.module
Implementation of hook_user().
blog_view in modules/blog/blog.module
Implementation of hook_view().
book_admin_edit_submit in modules/book/book.admin.inc
Handle submission of the book administrative page form.
book_admin_overview in modules/book/book.admin.inc
Returns an administrative overview of all books.
book_render in modules/book/book.pages.inc
Menu callback; prints a listing of all books.
chameleon_comment in themes/chameleon/chameleon.theme
chameleon_node in themes/chameleon/chameleon.theme
chameleon_page in themes/chameleon/chameleon.theme
comment_admin_overview in modules/comment/comment.admin.inc
Form builder; Builds the comment overview form for the admin.
comment_admin_overview_submit in modules/comment/comment.admin.inc
Process comment_admin_overview form submissions.
comment_reply in modules/comment/comment.pages.inc
This function is responsible for generating a comment reply form. There are several cases that have to be handled, including:
comment_save in modules/comment/comment.module
Accepts a submission of new or changed comment content.
confirm_form in modules/system/system.module
Generates a form array for a confirmation form.
contact_admin_categories in modules/contact/contact.admin.inc
Categories/list tab.
contact_admin_edit_submit in modules/contact/contact.admin.inc
Process the contact category edit page form submission.
dblog_event in modules/dblog/dblog.admin.inc
Menu callback; displays details about a log message.
dblog_overview in modules/dblog/dblog.admin.inc
Menu callback; displays a listing of log messages.
db_status_report in includes/database.mysqli.inc
Report database status.
db_status_report in includes/database.mysql.inc
Report database status.
filter_admin_format_form in modules/filter/filter.admin.inc
Generate a filter format form.
filter_admin_overview in modules/filter/filter.admin.inc
Menu callback; Displays a list of all input formats and which one is the default.
forum_nodeapi in modules/forum/forum.module
Implementation of hook_nodeapi().
forum_overview in modules/forum/forum.admin.inc
Returns an overview list of existing forums and containers
help_links_as_list in modules/help/help.admin.inc
hook_requirements in developer/hooks/install.php
Check installation requirements and do status reporting.
hook_view in developer/hooks/node.php
Display a node.
locale_update_6005 in modules/locale/locale.install
Change language setting variable of content types.
menu_edit_item in modules/menu/menu.admin.inc
Menu callback; Build the menu link editing form.
menu_get_active_breadcrumb in includes/menu.inc
Get the breadcrumb for the current page, as determined by the active trail.
node_admin_nodes in modules/node/node.admin.inc
Form builder: Builds the node administration overview.
node_feed in modules/node/node.module
A generic function for generating RSS feeds from a set of nodes.
node_form_submit in modules/node/node.pages.inc
node_overview_types in modules/node/content_types.inc
Displays the content type admin overview page.
node_revision_overview in modules/node/node.pages.inc
Generate an overview table of older revisions of a node.
node_title_list in modules/node/node.module
Gather a listing of links to nodes.
node_type_form_submit in modules/node/content_types.inc
Implementation of hook_form_submit().
openid_form_alter in modules/openid/openid.module
Implementation of hook_form_alter : adds OpenID login to the login forms.
openid_user_identities in modules/openid/openid.pages.inc
Menu callback; Manage OpenID identities for the specified user.
path_admin_overview in modules/path/path.admin.inc
Return a listing of all defined URL aliases. When filter key passed, perform a standard search on the given key, and return the list of matching URL aliases.
php_install in modules/php/php.install
Implementation of hook_install().
poll_page in modules/poll/poll.pages.inc
Menu callback to provide a simple list of all polls available.
profile_admin_overview in modules/profile/profile.admin.inc
Form builder to display a listing of all editable profile fields.
profile_block in modules/profile/profile.module
Implementation of hook_block().
profile_field_delete_submit in modules/profile/profile.admin.inc
Process a field delete form submission.
profile_field_form_submit in modules/profile/profile.admin.inc
Process profile_field_form submissions.
profile_view_field in modules/profile/profile.module
search_view in modules/search/search.pages.inc
Menu callback; presents the search form and/or search results.
statistics_access_log in modules/statistics/statistics.admin.inc
Menu callback; Displays recent page accesses.
statistics_node_tracker in modules/statistics/statistics.pages.inc
statistics_recent_hits in modules/statistics/statistics.admin.inc
Menu callback; presents the "recent hits" page.
statistics_top_visitors in modules/statistics/statistics.admin.inc
Menu callback; presents the "top visitors" page.
statistics_user_tracker in modules/statistics/statistics.pages.inc
system_actions_manage in modules/system/system.module
Menu callback. Display an overview of available and configured actions.
system_admin_by_module in modules/system/system.admin.inc
Menu callback; prints a listing of admin tasks for each installed module.
system_get_module_admin_tasks in modules/system/system.module
Generate a list of tasks offered by a specified module.
system_requirements in modules/system/system.install
Test and report Drupal installation requirements.
system_themes_form in modules/system/system.admin.inc
Menu callback; displays a listing of all themes.
tablesort_header in includes/tablesort.inc
Format a column header.
taxonomy_form_term_submit in modules/taxonomy/taxonomy.admin.inc
Submit handler to insert or update a term.
taxonomy_form_vocabulary_submit in modules/taxonomy/taxonomy.admin.inc
Accept the form submission for a vocabulary and save the results.
taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Form builder for the taxonomy terms overview.
taxonomy_overview_vocabularies in modules/taxonomy/taxonomy.admin.inc
Form builder to list and manage vocabularies.
taxonomy_term_page in modules/taxonomy/taxonomy.pages.inc
Menu callback; displays all nodes associated with a term.
template_preprocess_aggregator_feed_source in modules/aggregator/aggregator.pages.inc
Process variables for aggregator-feed-source.tpl.php.
template_preprocess_aggregator_item in modules/aggregator/aggregator.pages.inc
Process variables for aggregator-item.tpl.php.
template_preprocess_comment in modules/comment/comment.module
Process variables for comment.tpl.php.
template_preprocess_comment_folded in modules/comment/comment.module
Process variables for comment-folded.tpl.php.
template_preprocess_forums in modules/forum/forum.module
Process variables for forums.tpl.php
template_preprocess_forum_topic_list in modules/forum/forum.module
Preprocess variables to format the topic listing.
template_preprocess_user_picture in modules/user/user.module
Process variables for user-picture.tpl.php.
theme_admin_block_content in modules/system/system.admin.inc
This function formats the content of an administrative block.
theme_admin_page in modules/system/system.admin.inc
This function formats an administrative page for viewing.
theme_aggregator_block_item in modules/aggregator/aggregator.module
Format an individual feed item for display in the block.
theme_book_admin_table in modules/book/book.admin.inc
Theme function for the book administration page form.
theme_book_title_link in modules/book/book.module
Generate the HTML output for a link to a book title when used as a block title.
theme_comment_block in modules/comment/comment.module
Returns a formatted list of recent comments to be displayed in the comment block.
theme_filter_tips_more_info in modules/filter/filter.module
Format a link to the more extensive filter tips.
theme_links in includes/theme.inc
Return a themed set of links.
theme_locale_languages_overview_form in includes/locale.inc
Theme the language overview form.
theme_menu_item_link in includes/menu.inc
Generate the HTML output for a single menu link.
theme_node_add_list in modules/node/node.pages.inc
Display the list of available node types for node creation.
theme_pager_link in includes/pager.inc
Returns HTML for a link to a specific query result page.
theme_system_powered_by in modules/system/system.module
Format the Powered by Drupal text.
theme_update_report in modules/update/update.report.inc
Theme project status report.
theme_update_version in modules/update/update.report.inc
Theme the version display of a project.
theme_upload_attachments in modules/upload/upload.module
Displays file attachments in table
theme_username in includes/theme.inc
Format a username.
theme_user_admin_new_role in modules/user/user.admin.inc
Theme the new-role form.
tracker_page in modules/tracker/tracker.pages.inc
Menu callback. Prints a listing of active nodes on the site.
translation_node_overview in modules/translation/translation.pages.inc
Overview page for a node's translations.
trigger_assign_form in modules/trigger/trigger.admin.inc
Create the form definition for assigning an action to a hook-op combination.
user_admin_access in modules/user/user.admin.inc
Menu callback: list all access rules
user_admin_account in modules/user/user.admin.inc
Form builder; User administration page.
user_external_login_register in modules/user/user.module
Helper function for authentication modules. Either login in or registers the current user, based on username. Either way, the global $user object is populated based on $name.
user_login_block in modules/user/user.module
user_register_submit in modules/user/user.module
Submit handler for the user registration form.
_locale_translate_seek in includes/locale.inc
Perform a string search and display results in a table
_menu_overview_tree_form in modules/menu/menu.admin.inc
Recursive helper function for menu_overview_form().
_menu_site_is_offline in includes/menu.inc
Checks whether the site is off-line for maintenance.
_node_mass_update_batch_process in modules/node/node.admin.inc
Node Mass Update Batch operation
_statistics_link in modules/statistics/statistics.module
It is possible to adjust the width of columns generated by the statistics module.
_update_refresh in modules/update/update.fetch.inc
Fetch project info via XML from a central server.
_update_requirement_check in modules/update/update.module
Private helper method to fill in the requirements array.

File

includes/common.inc, line 1617
Common functions that many Drupal modules will need to reference.

Code

<?php
function l($text, $path, $options = array()) {
  global $language;

  // Merge in defaults.
  $options += array(
    'attributes' => array(), 
    'html' => FALSE,
  );

  // Append active class.
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) && 
      (empty($options['language']) || $options['language']->language == $language->language)) {
    if (isset($options['attributes']['class'])) {
      $options['attributes']['class'] .= ' active';
    }
    else {
      $options['attributes']['class'] = 'active';
    }
  }

  // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
    $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  }

  return '<a href="' . check_url(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
}
?>

Comments

It is not necessary to wrap

It is not necessary to wrap the $text argument with t() as long as the html option is FALSE (the default). l() will automatically check_plain() the link text for you.

check_plain() and t() are different

t() is necessary if you are providing translatable text. The purpose of t() is to provide translation, while check_plain() is used to escape any possible malicious character. Often t() is used an easy way to provide secure text since it pushes things through check_plain, but this is just an added bonus. use t() for translating!.

Example with custom class, attributes

This will produce a link with the class="widelink" and rel="lightbox" attributes on the a tag.

<?php
l
(
 
t('My link'),
 
'node/56',
  array(
   
'attributes' => array(
     
'class' => 'widelink',
     
'rel' => 'lightbox',
    )
  )
);
?>

Open link a in new window

All components are already mentioned but no example straight into you face, so to open link in new windows use:

<?php
  l
(t('Title'),$url, array('attributes' => array('target' => '_blank')));
?>

Hope this will save time for some of you.

Valid HTML

That's helpful but the HTML won't validate for strict doc types.

Something like the following code should work:

<?php
  l
(t('Title'), $url, array('attributes' => array('onclick' => 'window.open(this.href); return false;')));
?>

Links to an anchor, or hash-only links

To create a link to a named anchor (e.g. #namedanchor), you will need to use a small work-around.

<?php
  l
('linktext', '', array('fragment' => 'namedanchor', 'external' => TRUE));
?>

To create a hash-only link (to #), you'll need to adapt it to:

<?php
  l
('linktext', '', array('fragment' => ' ', 'external' => TRUE));
?>

(Note that the fragment does contain a space.)

how to prevent l() from screwing up an ubercart purchase link

In porting a D5 site to D6, I found within their Ubercart logic they are generating a purchase item image-link like this:

   $buy_img = theme_image('sites/all/themes/customTheme/images/buy.png', 'BUY', 'Buy The' . check_plain($node->title), array('class' => 'coins'));
    $buy_link = 'cart/add/e-p' . $node->nid . '_q1_m0?destination=cart/checkout';
    print l( $buy_img, $buy_link, array('html' => true) );

The problem is the l() function is supposed to generate this:

http://localhost/cart/add/e-p176_q1_m0?destination=cart/checkout

but is generating this incorrect link with character encoding rather than '?' and '=' characters:

http://localhost/cart/add/e-p176_q1_m0%3Fdestination%3Dcart/checkout

Apparently, the D5 l() function does not do that same character encoding, and was not an issue... So here's the fix for D6:

    $buy_link = 'cart/add/e-p' . $node->nid . '_q1_m0';
    print l( $buy_img, $buy_link, array('html' => true, 'query' => 'destination=cart/checkout') );

The solution being to place the query string portion of the link into a 'query' attribute.

Add permissions to view links

I thought this was helpful...

if (user_access('create blog entries')) {
    $items[] = l(t('Create new blog entry.'), "node/add/blog");
  }

Used in blog module function blog_page_last

Internal Module Links

To clarify for those who want their module to support the 'Clean URLs' option.

<?php
  $var
= l("Click Text", "ModuleName");
?>

returns a link complete with <a href= tags.

For a link that goes with your hook_menu() and 'page arguments' you just add the arguments to the path.

<?php
  $var
= l("Click Text", "ModuleName/value/value");
?>

If you need a link without the <a href= tags use 'url' instead.

<?php
  $var
= url("ModuleName/value/value")
?>

Examples

Various implementation of l() function

simple:

<?php
  l
(t('Link text'), 'about-us');
?>

with class:

<?php
  l
(t('Link text'), 'about-us', array('attributes' => array('class' => 'about-link')));
?>

link to user:

<?php
  l
(t($user->name), 'user/'.$user->uid, array('attributes' => array('class' => 'link', 'id' => 'xxx', 'title' => 'Title')));
?>

Always use user/user id!!!

simple link with image:

<?php
$img
= '<img src="'.$base_path . $directory . '/images/rssIcon.png" />';
l($img, 'user/3', array('html' => array('html' => 'true')));
// also valid
l($img, 'user/3', array('html' => 'true'));
?>

complex link with image:

<?php
l
($img, 'user/3', array('attributes' => array('class' => 'link', 'id' => 'xxx', 'title' => 'Title'), 'html' => 'true'));
?>

Some of those examples

*might* lead to security issues.. (I mean... sure I did some of those mistakes... back in the days... :) )

the l() function sanitize the first argument (the text) when the option "html" isn't TRUE...
it means that you need to really take care about what the first argument will be if using the "html" option

For example:

<?php
// making an img tag like might not be the safest solution
//$img = '<img src="'.$base_path . $directory . '/images/rssIcon.png" />';
// this would be much better, but still, you need to know that the $directory variable is also safe
$img = theme('image', $directory .'/images/rssIcon.png');
// this is, I think, not possible...
//l($img, 'user/3', array('html' => array('html' => 'true')));
// is ok
l($img, 'user/3', array('html' => 'true'));
?>

<?php
// well, stop me if I am wrong, but I guess might be useful to wrap $user->name within t()..
//l(t($user->name), 'user/'.$user->uid, array('attributes' => array('class' => 'link', 'id' => 'xxx', 'title' => 'Title')));
// Something who might be handy if you need to "define" an HTML id is the form_clean_id()
// it will prevent to have twice the same id in the HTML (which is bad :) )
l($user->name, 'user/'.$user->uid, array('attributes' => array('class' => 'link', 'id' => form_clean_id('xxx'), 'title' => 'Title')));
?>

Just a note..
if you need to have a variable in a translation.. like it might have been the case in the example

<?php
l
(t('Some string related to @user_name', array(
'@user_name' => $user->name
)), 'user/'. $user->uid);
// I might explain why it might be better to use @user_name over a simple @user... but it's not the topic ;)
?>

or...
<?php
theme
('username', $user);
// whatever..
?>

anyway, it was nice from you to help!

t() is only for translatable strings

I don't think it is a good idea to use t($user->name)

This may create a translatable string for each user name. The translator will never reach a hundred per cent translation unless he translates each username, and if he does so he will change a value he shouldn't change.

I'd suggest to use t() every time a string needs to be translated, and in no other circumstance.

in $options you forget to

in $options you forget to explain language options, to protect links against language prefix names like 'site.name.com/en/sites/defailt/files/blag.pdf'

I protect my site against this using below solution

<?php
$link
= l($title, $path, array('language' => 'pl'));
?>

'boxes' table in database

<?php
l
($img, 'user/3', array('attributes' => array('class' => 'link', 'id' => 'xxx', 'title' => 'Title'), 'html' => 'true'));
?>

For Drupal6

If you look at the description of the function in Drupal 6 parameters you will find under $options:

Additional $options elements used by the url() function.

But I was not able to put additional parameters into URL in this case:

print l("Click here", $internal_path, array(
   'listing_url' => 'data'
));

So I made the following changes as the user described above and it worked:

print l("Click here", $internal_path, array(
   'query' => array(
      'listing_url' => 'data'
    ),
));

Title and Alt attributes are sanitized

Actually all the "attributes" values are sanitized in drupal_attributes, so if you do anything to sanitize it yourself, you can end up double encoding. For example, l($title, $path, array('attributes' => array('title' => t('All about @names', array('@names' => 'Adam & Eve'))))) will result in the ampersand being double encoded. In this example, it is okay to use '!names' because drupal_attributes will do a check_plain for you.

Link to #

to create a hash-only link (to #) you'll need to adapt it to:
l('linktext', '', array('fragment' => ' ', 'external' => TRUE));
(note that fragment does contains a space.)

Thanks to alexanderpas!

Can't figure out how to

Can't figure out how to combine attributes and fragment, since I need both - the first one to apply a class, second one to generate proper URI to the comment. What is wrong in my code below?

<?php
$block_content
.= l(t('Conversate'), "node/$links->nid", array('attributes'=>array('class'=>'comment')), array('fragment' => "comment-$links->cid")).'</div>';
?>

I rewrote your code with the

I rewrote your code with the correct syntax (I think but have not tested)
Main problem was: 'fragment' should not be in another array but just a key of the $options array.

<?php
$block_content
.= l(t('Conversate'), "node/".$links->nid, array('attributes'=>array('class'=>'comment'), 'fragment' => "comment-".$links->cid).'</div>';
?>

If this code doesn't work, here is my code wich, I'm sure works. Hope it will help you

<?php
print l("<span>View responses</span>", "node/".$fields['nid']->content,
                array(
                   
'fragment' => 'responses',
                   
'attributes' => array (
                               
'class' => 'btn_arrow_blue'
                               
),
                   
'html' => TRUE

                   
)   
                );
?>

Pretty much the same: a "class" attribute, an anchor and some html in the label (that's why I need the 'html' => TRUE

It builds:

<a class="btn_arrow_blue" href="/node'spath#responses">
<span>View responses</span>
</a>

Properly using destination

If you want to use the l() function and provide the destination:

<?php
l
('Login first','user/login', array(
   
'query' => array(
     
'destination' => 'node/'. $node->nid
    
)
  )
);
?>

The above code will provide you with an anchor tag with the href pointed to user/login?destination=node/NID

This is only useful if you are linking to a page that consist of a form, and you want the user to be redirected to another page after submitting the form.

For all other options available, make sure to see the documentation for the url() function.

drupal_get_destination()

You can use the destination of the current page with drupal_get_destination() like so

<?php
l
(
 
t('edit'),
 
'node/'.$nid.'/edit',
  array(
   
'query' => drupal_get_destination()
  )
);
?>

Links with Javascript or jQuery

If you want to use a link like an event-handler, your code could look like this:

  $link =  l("Click me", $_GET['q'],  array("attributes" => array("title" => t("Click this link"), "onclick" => '$("div.element_with_onclick_event").trigger("click");'), 'fragment' => 'anything'));

This will create an HTML-Markup like this:

<a class="active" onclick="$(&quot;div.element_with_onclick_event&quot;).trigger(&quot;click&quot;);" title="Click this link " href="/current_path#anything">Click me</a>

When you click on this link, the Trigger-Event "Click" for div.element_with_onclick_event will be called...

Don't forget print

I thought it might help some people to say that sometimes you need to add print, like so:

<?php
  
print l(t('Link text'), 'node/10');
?>

Login or register to post comments