7 common.inc | l($text, $path, array |
4.6 common.inc | l($text, $path, $attributes = array(), $query = NULL, $fragment = NULL, $absolute = FALSE, $html = FALSE) |
4.7 common.inc | l($text, $path, $attributes = array(), $query = NULL, $fragment = NULL, $absolute = FALSE, $html = FALSE) |
5 common.inc | l($text, $path, |
6 common.inc | l($text, $path, $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.
However, for links enclosed in translatable text you should use t() and embed the HTML anchor tag directly in the translated string. For example:
t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
This keeps the context of the link title ('settings' in the example) for translators.
Parameters
string $text: The translated link text for the anchor tag.
string $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_plain() before it is inserted into the HTML anchor tag, to ensure well-formed HTML. See url() for more information and notes.
array $options: An associative array of additional options. Defaults to an empty array. It may contain the following elements.
- 'attributes': An associative array of HTML attributes to apply to the anchor tag. If element 'class' is included, it must be an array; 'title' must be a string; other elements are more flexible, as they just need to work in a call to drupal_attributes($options['attributes']).
- '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. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.
- 'language': An optional language object. If the path being linked to is internal to the site, $options['language'] is used 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
string An HTML string containing a link to the given path.
See also
url()
- actions_synchronize in includes/
actions.inc - Synchronizes actions that are provided by modules in hook_action_info().
- aggregator_form_category_submit in modules/
aggregator/ aggregator.admin.inc - Form submission handler for aggregator_form_category().
- aggregator_form_feed_submit in modules/
aggregator/ aggregator.admin.inc - Form submission handler for aggregator_form_feed().
- aggregator_view in modules/
aggregator/ aggregator.admin.inc - Displays the aggregator administration page.
- authorize.php in ./
authorize.php - Administrative script for running authorized file operations.
- FieldTranslationsTestCase::setUp in modules/
field/ tests/ field.test - Set the default field storage backend for fields created during tests.
- LocaleTranslationFunctionalTest::testJavaScriptTranslation in modules/
locale/ locale.test
File
- includes/
common.inc, line 2432 - Common functions that many Drupal modules will need to reference.
Code
function l($text, $path, array $options = array()) {
global $language_url;
static $use_theme = NULL;
// 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_url->language)) {
$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']);
}
// Determine if rendering of the link is to be done with a theme function
// or the inline default. Inline is faster, but if the theme system has been
// loaded and a module or theme implements a preprocess or process function
// or overrides the theme_link() function, then invoke theme(). Preliminary
// benchmarks indicate that invoking theme() can slow down the l() function
// by 20% or more, and that some of the link-heavy Drupal pages spend more
// than 10% of the total page request time in the l() function.
if (!isset($use_theme) && function_exists('theme')) {
// Allow edge cases to prevent theme initialization and force inline link
// rendering.
if (variable_get('theme_link', TRUE)) {
drupal_theme_initialize();
$registry = theme_get_registry(FALSE);
// We don't want to duplicate functionality that's in theme(), so any
// hint of a module or theme doing anything at all special with the 'link'
// theme hook should simply result in theme() being called. This includes
// the overriding of theme_link() with an alternate function or template,
// the presence of preprocess or process functions, or the presence of
// include files.
$use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
$use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
}
else {
$use_theme = FALSE;
}
}
if ($use_theme) {
return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
}
// The result of url() is a plain-text URL. Because we are using it here
// in an HTML argument context, we need to encode it properly.
return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
}
Comments
Class attributes must be array
Note that to attach a class to a link via the $attributes array, then the class element itself must also be an array (even if it contains a single element)
In other words, Drupal 6.x:
<?php
l(t('Link text'), 'about-us', array('attributes' => array('class' => 'about-link')));
?>
Drupal 7.x:
<?php
l(t('Link text'), 'about-us', array('attributes' => array('class' => array('about-link'))));
?>
So, are we to assume...
that multiple classes would be this:
<?php
l(t('Link text'), 'about-us', array('attributes' => array('class' => array('about-link','another-class'))));
?>
Nope
Nope, multiple classes seems to be this - one array key, multiple values separated by a space.
<?php
l(t('Link text'), 'about-us', array('attributes' => array('class' => 'about-link another-class')));
?>
Um, nope!
So that is correct for D6, @rjbrown99, but in D7 the 'class' attribute value must be an array (see the $options parameter explained above). Just see how
l()
manipulates the 'class' attribute in the function body above; that code will break if you pass a string as you suggested.Wrong:
<?php
l(t('Link text'), 'about-us', array('attributes' => array('class' => 'about-link another-class')));
?>
Right:
<?php
l(t('Link text'), 'about-us', array('attributes' => array('class' => array('about-link', 'another-class'))));
?>
class attribute as string
What's so perfidious about this is that something like
$options = array(
'attributes' => array (
'class' => 'my_class',
),
);
print l($mytitle,$myhref,$options);
seems to work in the first moment. But then if you click the link you will get:
The function l tries to add the class "active" to the array(!) $options['attributes']['class'].
I suggest to make the function l more robust by adding the following lines:
if (is_string($options['attributes']['class']))
$options['attributes']['class'] = explode(" ",$options['attributes']['class']);
And therby convert the string to an array. This would allow to submit even multiple classes as a space separated string, as one would write the class attribute directly into the html tag:
'attributes' => array (
'class' => 'my_class1 my_class2',
),
Going the correct way via the array would still be possible.
Check with "is_set"
Sorry, to avoid warnings, the suggested lines should read:
<?php
if (isset($options['attributes']['class']) && is_string($options['attributes']['class']))
$options['attributes']['class'] = explode(" ",$options['attributes']['class']);
?>
ajax links
Most of the time an ajax link is just a fragment:
href="#"
In order to accomplish this, use the 'fragment' in $options. ex:
<?php
l(t('Refresh'), '', array('attributes' => array('id' => 'refresh-link-id', 'class' => 'refresh-link'), 'fragment' => 'refresh'));
?>
This will output the following:
<a href="/#refresh" id="refresh-link-id" class="refresh-link">Refresh</a>
Create link with target='_blank'
l(t('View Map & Directions'), $map_address_url, array('attributes' => array('target'=>'_blank')))
Attach destination to link url
e.g. if url points to a page with a form, you'll be redirected to destination url
<?php
l('Title', 'url', array('query' => array('destination' => 'destination_url')))
?>
This creates:
<a href="url?destination=destination_url">Title</a>
Thanks!
This was a total life saver! Thanks for the tip!
More options at once
Combination of the above.
<?php
global $base_url;
print
l('<img src="' . render(file_create_url($node->field_image['en'][0]['uri'])) . '"/>',
$base_url . $node_url,
array(
'attributes' => array(
'id' => 'my-id',
'class' => 'my-class'
),
'query' => array(
'foo' => 'bar'
),
'fragment' => 'refresh',
'html' => TRUE
)
);
?>
Creates:
<a href="http://www.example.com/node/1?foo=bar#refresh" id="my-id" class="my-class"><img src="http://www.example.com/files/image.jpg"/></a>
Perfect
Now that's what I call a great comment. Shows the what/how and the final output. Thanks borgo!
watch out for error
borgo's code example contains an error, though
<?php
'attributes' => array(
'id' => 'my-id',
'class' => 'my-class'
),
<
?>
should read:
<?php
'attributes' => array(
'id' => 'my-id',
'class' => array('my-class')
),
<
?>
Classes must be placed in an array. See http://api.drupal.org/api/drupal/includes--common.inc/function/l/7#comme...
If you want a simple
If you want a simple anchor/fragment link (similar to what sirkitree said in the ajax links comment above), but with just the anchor (
href="#namedanchor"
), do something like the following:<?php
l(t('My Anchor Link'), '', array(
'fragment' => 'namedanchor',
'external' => TRUE,
'attributes' => array(
'title' => 'Title here.'
),
));
?>
This outputs:
<a href="#namedanchor" title="Title here.">My Anchor Link</a>
You cannot use the l() function to create a simple 'name' anchor, though (like
<a name="namehere"></a>
). For this, you'll need to create the link manually.To create a simple 'name' anchor
You can still use the
l()
function to create a simple'name'
anchor with an emptyhref
value. For this, just do the following:l('', '', array(
//'fragment' => 'nameanchor',
'external' => TRUE,
'attributes' => array(
//'title' => 'Title here.',
'name' => 'nameanchor',
),
)
);
This generates:
<a href="" name="nameanchor"></a>
To create a simple 'name' anchor - edited
Mmmm... yesterday in the preview, that last line showed in a different manner. It should look like this:
<a href="" name="nameanchor"></a>
Or this:
<a href="" name="nameanchor"></a>
hey geerlingguy
geerlingguy if i want to output such HTML:
BGM
what the l() function should like ? Thanks.
How about '<a href="edit?id=1">'
How about ''
link to javascript:void(0)
here is a hint to link to javascript:void(0)
l($text,'javascript:void(0)',array('fragment' => '','external'=>true));
D7 linked image
Change field and style name to suit your needs.
<?php
l(theme_image_style(array('path' => $variables['node']->field_logo['und']['0']['uri'], 'style_name' => '100x100')), 'node/' . $variables['node']->nid, array('html' => TRUE));
?>
Local anchor
If you want to link to a local anchor (# on the same page), it requires a bit of tweaking. Using an empty path will lead to the root of the site, so you need to pump in the current path using $_GET['q'].
This example will create a local link to the comments section of a node:
<?php
$link = l(t('Comments'), $_GET['q'], array('fragment' => 'comments'));
?>
In a node located on the address http://mysite.tld/my_node this will output http://mysite.tld/my_node#comments
Martin
Providing a link in a form
U Can provide the desired link and can redirect it to your desired page in a form by providing,
$form['name']['link'] = array (
'#type' => 'item',
'#markup' => l('ur desired text', 'ur destination url'),
);
dis works well in my website..!
How would I change Edit into
How would I change Edit into img src?
l(t('Edit'), 'node/' . $node->nid . '/webform/components/' . $cid, array('query' => drupal_get_destination())),
Set the option "html"=true
You would have to set the option html to TRUE
<?php
print l(
'<img src="image.jpg">',
'node/' . $node->nid . '/webform/components/' . $cid,
array(
'query' => drupal_get_destination(),
'html' => true,
)
);
?>
Add parameters to an existing URL
How could I pass parameters to a link ?
If i'm on the page /node/123, I'd like to create a link with an output such as /node/123?param=456. Having in mind that it should work on any node (by keeping the current page url).
Is there a "drupal way" or do I have to use pure PHP ?
Thanks
if statement in hyper link
hello everyone,
Need your help in fixing this issue.
Below mentioned code is used in template.
<?php
// echo $vars['node']->type; require_once 'librarypath/geoip.inc';
$gi = geoip_open("librarypath/GeoIP.dat",GEOIP_STANDARD);
$location = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
?>
and my link is like this:
<?php
if($location == 'US') { echo 'pricing-others'; } else { echo 'pricing'; }
?>
">
I want to call the above hyperlink in my content page. how to call this. Kindly reply ASAP. This is bit urgent.
Thanks in advance....
if statement in hyper link
hello everyone,
Need your help in fixing this issue.
Below mentioned code is used in template.
<?php
// echo $vars['node']->type; require_once 'librarypath/geoip.inc';
$gi = geoip_open("librarypath/GeoIP.dat",GEOIP_STANDARD);
$location = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
?>
and my link is like this:
<?php
if($location == 'US') { echo 'pricing-others'; } else { echo 'pricing'; }
?>
">
I want to call the above hyperlink in my content page. how to call this. Kindly reply ASAP. This is bit urgent.
Thanks in advance....
l(t('mytext'),'path'); not working in php block
I used
<?php
l(t('mytext'),'path');
?>
in block content with php format, i sured that the php code run correctly but dont get any result .
find out
<?php
print l(t('mytext'),'path');
?>
;)
Try this. l('click here',
Try this.
l('click here', 'node/123', array('query' => array('param' => 456)));
thanks - good solution for adding a parameter
This worked, where
l('click here', 'node/123?param=456');
doesn't.
Destination
I noticed a few have difficulties with destination.
Here's a proper way to do this:
<?php
$destination = drupal_get_destination();
l('Login', 'user/login', array('query' => array($destination)));
?>
You'll notice that
'query'
is not set toarray('destination' => $destination)
; that's becausedrupal_get_destination()
already returns an array. I.e.drupal_get_destination()
=array('destination' => '/destination-path')
.An example of using the HTML option on the l() function
<?php
// The following produces a link such as "<a href='flipcard/start_set/2'><button>Study this set</button></a>"
print l('<button>' . t('Study this set') . '</button>', 'flipcard/start_set/' . $term->tid, array('html' => TRUE));
?>
Add css class
l( t('Refresh Page'), $path . '/getdata', array(
'attributes' => array(
'id' => '',
'class' => 'btn-small btn-primary '
),'query' => drupal_get_destination() , 'html' => TRUE)),
);
the line with class should
the line with class should rather be:
<?php
'class' => array('btn-small', 'btn-primary '),
?>
See my posting above: http://api.drupal.org/comment/47838#comment-47838
Why are we running strip_tags() here?
I was wondering why the
l()
function removes all HTML and PHP tags in the title attribute.The
drupal_attributes()
function called below will run all of the attributes acrosscheck_plain()
which should do the job. This filtering seems unnecessary (CPU consuming) and may break the rendering of the desired tooltip.What about if I would like to create a link with a tooltip such as this?
Pass over me
I would prefer doing this the
I would prefer doing this the old fashioned way:
title="<< This is not the best example >>"