[markdown_to_html] option to open external links in another tab
Is there a way to add an option so that external link have a target="blank" added to the a tag?
For example,
[Cleveland Museum of Art](https://github.com/ClevelandMuseumArt/openaccess),
[Metropolitan Museum of Art](https://github.com/metmuseum/openaccess) and
I know I can simply embed html instead, but this seems like a handy feature.
Extending that idea, is there a way I can intercept and render any link tag? For styling, adding an icon, etc.?
The conversion of markdown to HTML is not performed by Twig itself.
The MarkdownExtension relies on an external markdown engine (see the MarkdownInterface and its different implementations for the supported engines). Some of those engines may be providing such extension points.
If you use commonmark you can use the ExternalLinkExtension extension.
https://commonmark.thephpleague.com/2.5/extensions/external-links/
You have to create your own factory:
final class YourLeagueCommonMarkConverterFactory
{
private $extensions;
/**
* @param ExtensionInterface[] $extensions
*/
public function __construct(
#[TaggedIterator(tag: 'twig.markdown.league_extension')]
iterable $extensions
) {
$this->extensions = $extensions;
}
public function __invoke(): CommonMarkConverter
{
$config = [
'external_link' => [
'internal_hosts' => 'www.internal.host',
'open_in_new_window' => true,
],
];
$converter = new CommonMarkConverter($config);
foreach ($this->extensions as $extension) {
$converter->getEnvironment()->addExtension($extension);
}
return $converter;
}
}
service.yaml
League\CommonMark\Extension\ExternalLink\ExternalLinkExtension:
tags:
- { name: 'twig.markdown.league_extension' }
twig.markdown.league_common_mark_converter_factory:
class: App\YourLeagueCommonMarkConverterFactory
I haven't tried it, but the principle looks something like this. What I don't like about the solution is that you need your own factory to configure the CommonMark environment. This could be improved. The config argument should be a param to configure the environment.
I found the PR that fixes the complicated setup: https://github.com/twigphp/Twig/pull/3737
Thanks, @connorhu!
#3737 has been merged now.
Thanks! I don't see external_links as a option under commonmark, so I'm not sure how to configure it.
https://commonmark.thephpleague.com/2.3/extensions/external-links/#usage
Looking at the PR: https://github.com/twigphp/Twig/commit/3cdf26fe76f18fb5ea9da8fa0e87f50ea11adcf6
Also, is there a way to pass arguments to the renderer in twig?
{% if item.description ?? false %}
<p>{{ item.description|default()|markdown_to_html(external_link: 'open_in_new_window') }}</p>
{% endif %}