Skip to content

My solution for anchor links #927

@4project-co-il

Description

@4project-co-il

To those who need to add some anchor links to their MD text. For content tables or other purposes.
Here's my take on that subject:

Current Parsedown alows adding links to the anchors with:

[Link to anchor](#anchor_target)

I was facing a problem with addition of the anchor link itself to the MD text.
Adding an HTML tag directly didn't work for me, regardless the safe mode or markup escapes.
My solution was to extend the inlineLink function implementation, where I check that the link had no text specified and the href doesn't start with http as it happens for the images.
When such element is detected, I replace the href to name attribute, so I can specify anchors with that MD tag:

[](anchor_target)

And here's the code for the extention:

class ParsesownExtension extends \Parsedown
{
	protected function inlineLink($Excerpt)
	{
		$link = parent::inlineLink($Excerpt);

		if (! isset($link)) {
			return null;
		}

		if ($link['element']['handler']['argument'] == '' &&
			strpos($link['element']['attributes']['href'], 'http') !== 0) {
			// Link without a title/argument and doesn't start with 'http' like images,
			// make it anchor link (with name attribute instead of href)
			$link['element']['attributes']['name'] = $link['element']['attributes']['href'];
			unset($link['element']['attributes']['href']);
		}

		return $link;
	}
}

Enjoy.

And thanks to the authors.
Too bad I didn't choose the MD from the start for my content management, instead of the BBCodes...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions