bluetel-solutions/twig-truncate-extension

Twig Extension to truncate nested HTML, safely!

v0.1.3 2016-01-18 22:41 UTC

This package is not auto-updated.

Last update: 2024-05-01 16:18:26 UTC


README

Build Status

This extension attempts to solve a common problem, namely that of truncating HTML content based on the number of characters and on the number of words contained.

Other libraries we have tried attempt to manipulate the HTML content by means of regular expressions which is liable to break, and always seems to at the worst times, hence the need for this extension. This leverages the power of DOMDocument to safely truncate even the most complex of nested HTML documents.

Truncating on word count

{% set html %}
    <h1>Test heading!</h1>
    <ul>
        <li>Hello world</li>
        <li>Foo bar</li>
        <li>Lorem Ipsum</li>
    </ul>
{% endset html %}
{{ html|truncate_words(5) }}

Running this returns:

<h1>Test heading!</h1>
<ul>
    <li>Hello world</li>
    <li>Foo</li>
</ul>

Truncating on character count

{% set html %}
    <h1>Test heading!</h1>
    <ul>
        <li>Hello world</li>
        <li>Foo bar</li>
        <li>Lorem Ipsum</li>
    </ul>
{% endset html %}
{{ html|truncate_letters(20) }}

Whereas running the above returns the following:

<h1>Test heading!</h1>
<ul>
    <li>Hello wo</li>
</ul>