Twig extension for Url highlight library
Using Symfony? There is a bundle available: Url highlight symfony bundle
Install the latest version with:
$ composer require vstelmakh/url-highlight-twig-extension
Add extension to your twig environment:
<?php
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use VStelmakh\UrlHighlight\UrlHighlight;
use VStelmakh\UrlHighlightTwigExtension\UrlHighlightExtension;
// create twig environment
$loader = new FilesystemLoader('/path/to/templates');
$twig = new Environment($loader, []);
// add extension
$urlHighlight = new UrlHighlight();
$twig->addExtension(new UrlHighlightExtension($urlHighlight));
Use urls_to_html
filter in your templates:
{{ 'Basic example http://example.com'|urls_to_html }}
{# output: Basic example <a href="http://example.com">http://example.com</a> #}
To properly handle HTML entity escaped string, use Encoder. See configuration example below.
Warning: the filter considers the input string being already safe, and it will print any HTML tag in it. It is the developer's responsability to sanitise the input before passing it to urls_to_html
.
Additional options could be provided via UrlHighlight constructor. For more details see: Url highlight configuration.
Example:
<?php
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use VStelmakh\UrlHighlight\Encoder\HtmlSpecialcharsEncoder;
use VStelmakh\UrlHighlight\UrlHighlight;
use VStelmakh\UrlHighlightTwigExtension\UrlHighlightExtension;
$loader = new FilesystemLoader('/path/to/templates');
$twig = new Environment($loader, []);
$encoder = new HtmlSpecialcharsEncoder();
$urlHighlight = new UrlHighlight(null, null, $encoder);
$twig->addExtension(new UrlHighlightExtension($urlHighlight));
Now escaped input will be handled properly:
{{ '<a href="http://example.com?a=1&b=2">Example</a>'|escape|urls_to_html }}
{# output: <a href="<a href="http://example.com?a=1&b=2">http://example.com?a=1&b=2</a>">Example</a> #}
Volodymyr Stelmakh
Licensed under the MIT License. See LICENSE for more information.