tags:

views:

626

answers:

3

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

+2  A: 

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'));
Jeremy French
+6  A: 

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.

googletorp
perfect, thanks!
AK
A: 

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 questions