Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twig Truncate Extension Laravel Package

dzango/twig-truncate-extension

Twig extension that truncates text while preserving HTML tags. Adds a truncate filter with options for length, ending, exact word cutting, and HTML handling—works with rendered markdown or raw content. Easy to register in Twig or Symfony2.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require dzango/twig-truncate-extension
    
  2. Register the Extension (Laravel 5.5+): Add to config/app.php under providers:

    Dzango\Twig\Extension\TruncateServiceProvider::class,
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Dzango\Twig\Extension\TruncateServiceProvider"
    

    Laravel 5.4 or older: Manually register in app/Providers/AppServiceProvider:

    public function register()
    {
        $this->app['twig']->addExtension(new \Dzango\Twig\Extension\Truncate());
    }
    
  3. First Use Case: Truncate a string in a Blade template:

    {{ $longText|truncate }}
    

    Output: First 100 characters (excluding HTML tags) with ... appended.


Implementation Patterns

Core Workflows

  1. Basic Truncation:

    {{ $article->content|truncate(50) }}  {# 50 chars, default ending #}
    
    {{ $comment|truncate(30, ' [read more]') }}  {# Custom ending #}
    
  2. HTML-Preserving Truncation:

    {{ "<p>This <strong>is</strong> a <a href='#'>test</a>.</p>"|truncate(20, '', false, true) }}
    

    Output: <p>This <strong>is</strong> a </p> (preserves <a> tag).

  3. Markdown Integration:

    {{ $markdownText|markdown|raw|truncate(80) }}
    

    Note: Use raw to prevent double-encoding after markdown conversion.

  4. Dynamic Lengths:

    {{ $text|truncate($dynamicLength) }}
    

    Pass a variable (e.g., from a config or user preference).

  5. Exact Truncation:

    {{ $text|truncate(100, '', true) }}  {# Force exact length, even mid-word #}
    

Laravel-Specific Patterns

  • Service Container Binding: Bind the extension globally in AppServiceProvider:

    $this->app->singleton(\Dzango\Twig\Extension\Truncate::class, function ($app) {
        return new \Dzango\Twig\Extension\Truncate(config('truncate.defaults'));
    });
    

    Configure defaults in config/truncate.php:

    return [
        'length' => 120,
        'ending' => '...',
        'exact' => false,
        'consider_html' => true,
    ];
    

    Use in Blade:

    {{ $text|truncate }}  {# Uses config defaults #}
    
  • Eloquent Scopes: Combine with Eloquent for database-level truncation (e.g., in a toSearchableArray accessor):

    public function getSearchableContentAttribute()
    {
        return Str::of($this->content)->truncate(150)->toString();
    }
    
  • API Responses: Truncate content in JSON responses:

    return response()->json([
        'title' => $post->title,
        'teaser' => $post->content|truncate(100),
    ]);
    

    Note: Use a custom Blade directive or Laravel’s Str::of() for non-Twig contexts.


Gotchas and Tips

Pitfalls

  1. Double Encoding:

    • Issue: Truncating HTML-encoded strings (e.g., from htmlspecialchars) may break tags.
    • Fix: Decode first or use raw:
      {{ $encodedText|raw|truncate }}
      
  2. Nested HTML:

    • Issue: Complex nested tags (e.g., <div><span>...</span></div>) may not truncate cleanly.
    • Fix: Test edge cases; adjust length or use considerHtml=false for strict truncation.
  3. Markdown Parsing:

    • Issue: Some markdown parsers (e.g., parsedown) may output malformed HTML.
    • Fix: Sanitize with Str::of($text)->markdown()->toHtml() before truncating.
  4. Performance:

    • Issue: Heavy truncation in loops (e.g., 1000 items) may slow rendering.
    • Fix: Cache truncated results or truncate at the database level (e.g., with a TEASER column).
  5. Laravel Mix/Blade Caching:

    • Issue: Cached Blade views may not reflect config changes (e.g., truncate.length).
    • Fix: Clear cache:
      php artisan view:clear
      

Debugging Tips

  • Inspect Truncated Output: Use {{ $text|truncate|e('htmlspecialchars') }} to debug hidden characters.
  • Log Parameters: Override the extension to log calls:
    $twig->addExtension(new class extends \Dzango\Twig\Extension\Truncate {
        public function getTruncated($string, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
            \Log::debug("Truncate called with: length=$length, exact=$exact");
            return parent::getTruncated($string, $length, $ending, $exact, $considerHtml);
        }
    });
    

Extension Points

  1. Custom Truncation Logic: Extend the Truncate class to add features (e.g., word-based truncation):

    class CustomTruncate extends \Dzango\Twig\Extension\Truncate {
        public function getWordTruncated($string, $words = 10, $ending = '...') {
            // Custom logic here
        }
    }
    
  2. Twig Filter Aliases: Register an alias for readability:

    $twig->addFunction(new \Twig\TwigFunction('teaser', [$this, 'getTruncated']));
    

    Usage:

    {{ $text|teaser(80) }}
    
  3. Integration with Laravel Collectives: Use with HTML::entityDecode() for encoded strings:

    {{ $encodedText|raw|entityDecode|truncate }}
    

Configuration Quirks

  • Default Values: Override defaults in config/truncate.php:
    'defaults' => [
        'length' => 150,
        'ending' => ' <a href="#">...read more</a>',
    ],
    
  • Symfony/Twig Environment: If using Symfony’s Twig bundle, ensure the service is tagged:
    tags:
        - { name: twig.extension, alias: truncate }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
monarobase/country-list
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity