Drupal: Creating anchor only link with l()

Viewed 19834

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 of www.example.com/currentpage#namedanchor

3 Answers

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>
Related