Drupal: Creating anchor only link with l()
Solution 1
If you want to create a link with just the fragment, you need to "trick" the url function a bit. As it will append the basepath to all internal urls, ''
will become http://example.com
.
What you need to do is to set the external option to true:
l('link', '', array('fragment' => 'namedanchor', 'external' => TRUE));
This will give the desired
<a href='#namedanchor'>link</a>
Alternative you could give the full url like Jeremy suggests.
Solution 2
To create an anchor using l():
$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
l(t('link text'), $path, array('attributes' => array('name' => 'name-of-anchor')));
This will output:
<a href="/path/to/currentpage" name="name-of-anchor">link text</a>
Then, to link to this using l():
$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
l(t('link to anchor'), $path, array('fragment' => 'name-of-anchor'));
This will output:
<a href="/path/to/currentpage#name-of-anchor">link to anchor</a>
Solution 3
Here is the documentation for l
It dosn't look like it will by default use the current page when no path is defined. So you should call it like this:
l('link', 'currentpage', array('fragment' => 'namedanchor'));
Related videos on Youtube
ack
Updated on February 24, 2020Comments
-
ack about 4 years
I'd like to output this
<a href='#namedanchor'>link</a>
using the l() function, so that the link just jumps to an anchor on the current page.
I expected this to work
l('link', '', array('fragment' => 'namedanchor'));
but it creates an absolute link to
www.example.com/#namedanchor
instead ofwww.example.com/currentpage#namedanchor
-
cdmo almost 7 yearsprobably should add
t()
function around the first argument inl()
, right?