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

Technical Evaluation

Architecture Fit

  • Twig Integration: The package is a Twig extension, making it a natural fit for Laravel applications leveraging Blade templating (which underpins Twig-like syntax). Laravel’s Blade engine does not natively support Twig filters, but this package can be adapted via custom Blade directives or by integrating Twig as a secondary templating engine (e.g., via twig/bridge).
  • HTML-Aware Truncation: The core value proposition—preserving HTML tags while truncating text—aligns with use cases like:
    • Dynamic content rendering (e.g., excerpts, previews).
    • SEO-friendly snippets (e.g., meta descriptions, social shares).
    • Markdown-to-HTML pipelines where raw content must remain intact.
  • Lightweight: The package is minimal (~100 lines of code), reducing bloat and risk of conflicts.

Integration Feasibility

  • Blade Compatibility:
    • Option 1 (Recommended): Use Laravel’s Blade::directive() to create a custom truncate directive that wraps the Twig extension’s logic. Example:
      Blade::directive('truncate', function ($expression) {
          $truncate = new \Dzango\Twig\Extension\Truncate();
          return "<?php echo \$truncate->getTruncateToken()->getNode()->getNode($expression)->render(1); ?>";
      });
      
      Usage: @truncate($string, 100, '...')
    • Option 2: Integrate Twig as a secondary engine (higher complexity, but enables full Twig filter support).
  • Symfony Bundle: The TwigTruncateBundle simplifies integration in Symfony/Lumen but adds dependency overhead for Laravel.

Technical Risk

  • Blade vs. Twig Syntax: Laravel’s Blade does not natively support Twig filters, requiring custom logic (minor risk).
  • HTML Parsing Edge Cases: The truncation logic may fail with:
    • Malformed HTML (e.g., unclosed tags).
    • Complex nested structures (e.g., <table> with <thead>/<tbody>).
    • Non-standard HTML (e.g., SVG, custom elements).
    • Mitigation: Test with real-world content; consider pre-sanitizing input (e.g., with domdocument).
  • Performance: Truncation involves DOM parsing, which is heavier than string operations. Benchmark for high-throughput use cases (e.g., API responses).
  • Dependency Versioning: The package targets Twig ~1.0, which may conflict with Laravel’s bundled Twig (if using TwigBridge). Pin versions explicitly in composer.json.

Key Questions

  1. Use Case Priority:
    • Is HTML preservation critical (e.g., for SEO snippets), or could a simpler string truncation (e.g., Str::limit()) suffice?
    • Will this replace existing truncation logic (e.g., custom helper functions)?
  2. Templating Strategy:
    • Should we extend Blade or adopt Twig for this feature?
    • If Blade, how will we handle the directive’s arguments (e.g., {{ $text|truncate(50, '...') }} vs. @truncate($text, 50, '...'))?
  3. Testing:
    • What HTML edge cases must we validate (e.g., <a href="...">, <img src="...">)?
    • How will we test performance under load?
  4. Maintenance:
    • Who will own this package’s updates (e.g., if Twig deprecates APIs)?
    • Should we fork or contribute upstream?

Integration Approach

Stack Fit

  • Laravel 8+/9+: Ideal for Blade directive integration or TwigBridge adoption.
  • Lumen: Requires manual Twig environment setup (higher effort).
  • Symfony/Laravel Hybrid: Use TwigTruncateBundle if already using Symfony components.
  • Alternative: For simpler needs, Laravel’s Str::limit() may suffice (no HTML awareness).

Migration Path

  1. Assessment Phase:
    • Audit existing truncation logic (e.g., custom helpers, JavaScript solutions).
    • Identify high-priority use cases (e.g., blog excerpts, API responses).
  2. Prototype:
    • Implement a Blade directive (Option 1) or TwigBridge integration (Option 2).
    • Test with sample content (mix of plain text, HTML, and Markdown).
  3. Pilot:
    • Replace one truncation use case (e.g., blog post excerpts).
    • Measure performance and edge-case coverage.
  4. Rollout:
    • Gradually replace other truncation instances.
    • Deprecate old logic with feature flags.

Compatibility

  • Laravel Versions:
    • Tested on Laravel 8+ (Twig 2.x). For Laravel 7, use Twig 1.x compatibility mode.
    • Avoid conflicts with twig/twig or twig/bridge by pinning versions.
  • PHP Versions: Requires PHP 7.4+ (Twig 2.x minimum).
  • Dependencies:
    • No hard dependencies beyond Twig, which may already be present (e.g., in Laravel Fortify or Nova).

Sequencing

  1. Phase 1 (Low Risk):
    • Add package via Composer.
    • Implement Blade directive for basic truncation.
    • Test with static HTML content.
  2. Phase 2 (Medium Risk):
    • Extend to handle Markdown (via Str::markdown() + raw filter).
    • Validate edge cases (e.g., nested tags, entities like &nbsp;).
  3. Phase 3 (High Risk):
    • Integrate with dynamic content (e.g., API responses, CMS fields).
    • Benchmark performance; optimize if needed (e.g., caching truncated results).

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor dzango/twig-truncate-extension for updates (MIT license allows forks if needed).
    • Twig version compatibility may require re-testing after major Laravel releases.
  • Custom Logic:
    • Blade directives require manual updates if Laravel changes its templating engine.
    • If using TwigBridge, maintain Twig environment configurations.
  • Fallbacks:
    • Provide a fallback truncation method (e.g., Str::limit()) for when HTML parsing fails.

Support

  • Debugging:
    • HTML truncation issues may require inspecting the DOM structure (use browser dev tools or var_dump()).
    • Log edge cases (e.g., malformed HTML) to improve input validation.
  • Documentation:
    • Add usage examples to the project’s internal docs (e.g., Blade directive syntax, argument defaults).
    • Document limitations (e.g., "does not handle <script> tags safely").
  • Community:
    • Limited upstream support (package has 12 stars, no maintainer listed). Plan for self-support or forking.

Scaling

  • Performance:
    • Single Request: Truncation adds ~1–5ms per call (negligible for most apps).
    • Bulk Operations: For high-throughput scenarios (e.g., generating snippets for 10K+ items), consider:
      • Caching truncated results (e.g., Redis).
      • Pre-truncating content during storage (e.g., database column excerpt).
    • Alternatives: For extreme scale, use client-side truncation (JavaScript) or a dedicated service.
  • Horizontal Scaling:
    • No impact; truncation is stateless and occurs during rendering.

Failure Modes

Failure Scenario Impact Mitigation
Malformed HTML crashes truncation Broken templates, 500 errors Input sanitization (e.g., strip_tags() fallback).
Twig extension not loaded Filter/directive fails silently Validate Twig environment setup in tests.
Performance degradation under load Slow response times Cache truncated results; optimize HTML parsing.
Twig version incompatibility Package breaks after Laravel update Pin Twig version in composer.json.
Blade directive syntax errors Runtime exceptions Comprehensive test suite for directive usage.

Ramp-Up

  • Developer Onboarding:
    • Time to Adopt: 1–2 hours for Blade directive setup; 4–8 hours for TwigBridge.
    • Documentation: Add a short guide for the team (e.g., "Use @truncate($text, 100) for HTML-aware truncation").
  • Testing:
    • Unit Tests: Mock the truncation logic to test Blade directives.
    • Integration Tests: Validate with real templates (e.g., blog views).
    • E2E Tests: Check rendered
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.
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
testo/bridge-symfony