Symfony1 had a helper function called auto_link_text()
, which parsed a block of text and wrapped all text URLs in <a>
tags, automatically populating the href
attribute.
Does Twig include a function like this? I've looked on Google, and gone through the code, but can't find one. I can obviously code one myself, but don't want to replicate something if it's already there.
If I do code one myself, should it be a function or a filter?
The other listed "answer" is a little out of date and has issues. This one will work in the latest versions of Symfony and has less issues
class AutoLinkTwigExtension extends AbstractExtension
{
public function getFilters()
{
return [new TwigFilter('auto_link', [$this, 'autoLink'], [
'pre_escape'=>'html',
'is_safe' => ['html']])];
}
static public function autoLink($string)
{
$pattern = "/http[s]?:\/\/[a-zA-Z0-9.\-\/?#=&]+/";
$replacement = "<a href=\"$0\" target=\"_blank\">$0</a>";
$string = preg_replace($pattern, $replacement, $string);
return $string;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With