PHP code example of md-php / bridge-twig-html-truncation

1. Go to this page and download the library: Download md-php/bridge-twig-html-truncation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

md-php / bridge-twig-html-truncation example snippets


# Initialize extension
$truncate  = new \MD\HTML\Action\Truncate();
$extension = new \MD\Bridge\Twig\HTML\Extension\TruncateExtension(truncate: $truncate);

# Initialize component
$loader = new \Twig\Loader\ArrayLoader(templates: []);  // ... just example loader
$twig   = new \Twig\Environment(loader: $loader);

# Usage
$twig->addExtension(extension: $extension);

/**
 * Truncates HTML code to concrete length of text, taking care about correct removal of rest of elements and
 * element tags close.
 *
 * The content of element where given max length is reached truncated with adding `$ending` parameter content.
 * All next siblings elements and child are removed from the result.
 * Space characters in the begging or the in end of element text is not counted.
 *
 * @param  string $html      Source HTML code to truncate
 * @param  int    $maxLength Max length of text characters in HTML code to keep until truncation. Unsigned int.
 * @param  string $ending    Content to append to the truncated text, by default is ellipsis `...`
 * @return string            Truncated HTML code.
 *
 * @throws TruncateException
 */
function withTextLength(string $html, int $maxLength, string $ending = '...'): string;