Does Twig include a filter for automatically linking text?

Symfony1 had a helper function called auto_link_text() that parsed a block of text and completed all the text URLs in the <a> tags, automatically populating the href attribute.

Does Twig include this feature? I looked at Google and went through the code, but cannot find it. Obviously, I can encode it myself, but I don’t want to copy something if it already exists.

If I am the code myself, should it be a function or a filter?

+8
symfony twig
source share
2 answers

the function does not exist in the branch, but you can even add your own extensions in Twig:

 class AutoLinkTwigExtension extends \Twig_Extension { public function getFilters() { return array('auto_link_text' => new \Twig_Filter_Method($this, 'auto_link_text', array('is_safe' => array('html'))), ); } public function getName() { return "auto_link_twig_extension"; } static public function auto_link_text($string) { $regexp = "/(<a.*?>)?(https?)?(:\/\/)?(\w+\.)?(\w+)\.(\w+)(<\/a.*?>)?/i"; $anchorMarkup = "<a href=\"%s://%s\" target=\"_blank\" >%s</a>"; preg_match_all($regexp, $string, $matches, \PREG_SET_ORDER); foreach ($matches as $match) { if (empty($match[1]) && empty($match[7])) { $http = $match[2]?$match[2]:'http'; $replace = sprintf($anchorMarkup, $http, $match[0], $match[0]); $string = str_replace($match[0], $replace, $string); } } return $string; } } 
+14
source share

If you use a branch inside Symfony2, there is a package for this: https://github.com/liip/LiipUrlAutoConverterBundle

If you use it outside of Symfony2, you can send them a PR to separate the bundle and branch extension!

+10
source share

All Articles