vstelmakh/url-highlight-twig-extension

Twig extension for Url highlight library

v3.0.0 2020-11-05 21:20 UTC

This package is auto-updated.

Last update: 2024-03-27 20:06:07 UTC


README

Build status Packagist version PHP version License

Twig extension for Url highlight library

Installation

Using Symfony? There is a bundle available: Url highlight symfony bundle

Install the latest version with:

$ composer require vstelmakh/url-highlight-twig-extension

Setup

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));

Usage

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.

Configuration

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: &lt;a href=&quot;<a href="http://example.com?a=1&b=2">http://example.com?a=1&amp;b=2</a>&quot;&gt;Example&lt;/a&gt; #}

Credits

Volodymyr Stelmakh
Licensed under the MIT License. See LICENSE for more information.