Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Twig include a filter for auto-linking text?

Tags:

twig

symfony

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?

like image 493
Dan Blows Avatar asked May 26 '12 19:05

Dan Blows


1 Answers

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;
    }
}
like image 63
joshpme Avatar answered Nov 11 '22 05:11

joshpme