Is there a latte filter for turning urls into clickable links?

netteman
Member | 122
+
0
-

Hi,

is there a latte filter that would turn urls into clickable links like nette forum does?

I know I can get it done by JavaScript e.g. http://benalman.com/…/js-linkify/ but I'd like to know if Latte can do it.

Thanks ;-)

Ondřej Kubíček
Member | 494
+
0
-

no

Felix
Nette Core | 1186
+
0
-

No problem to create it. For example in contributte/latte.

Phalanx
Member | 310
+
0
-

@netteman So far as I know – no, but you can always create your own latte filter.

<?php
{$someContent|makeLinks}

class MyHelpers
{
	public static function loader($name, $s)
	{
		if (method_exists(__CLASS__, $name)) {
			return self::$name($s);
		}

		return NULL;
	}

	public static function makeLinks($content)
	{
		// something from here https://stackoverflow.com/questions/1960461/convert-plain-text-urls-into-html-hyperlinks-in-php
	}
}

// and register that helper
$template->registerHelper('makeLinks', callback('MyHelpers::makeLinks'));

?>
netteman
Member | 122
+
0
-

Thanks, guys!

netteman
Member | 122
+
+2
-

Here's my final code:

Presenter:

    protected function beforeRender()
    {
        parent::beforeRender();

        $this->template->addFilter('urlify', function ($s) {
			//preg source: https://stackoverflow.com/questions/1960461/convert-plain-text-urls-into-html-hyperlinks-in-php
            $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
            $s = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $s);
            return $s;
        });

    }
With escaping

    protected function beforeRender()
    {
        parent::beforeRender();

        $this->template->addFilter('urlify', function ($s) {
            $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
            $s = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8'));

            $html = new \Nette\Utils\Html;
            $html->setHtml($s);
            return $html;

        });
	}
Template:

	{$text|urlify|noescape}

Last edited by netteman (2018-08-23 10:13)

David Matějka
Moderator | 6445
+
+3
-

@netteman it is insecure, check how breaklines filter is implemented. to prevent xss you have to escape $s input first. also it is better to return Html instance, then you can remove noescape modifier in latte

netteman
Member | 122
+
0
-

David Matějka wrote:

@netteman it is insecure, check how breaklines filter is implemented. to prevent xss you have to escape $s input first. also it is better to return Html instance, then you can remove noescape modifier in latte

Thanks for the warning. I tested XSS with <script>alert(‘Hack!’);</script> AFTER I added breaklines filter which escaped the XSS so I thought everything was fine.

See the updated code above :)

Last edited by netteman (2018-08-23 14:13)