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 Bundle Laravel Package

dzango/twig-truncate-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dzango/twig-truncate-bundle
    

    For Symfony 4+, the bundle auto-enables. For older versions, manually register it in config/bundles.php or AppKernel.php.

  2. First Use Case: Truncate a string while preserving HTML tags in a Twig template:

    {{ 'This is a <b>long</b> text to truncate...'|truncate(20, '...') }}
    

    Output: This is a <b>long</b>...

  3. Where to Look First:


Implementation Patterns

Common Workflows

  1. Basic Truncation:

    {{ article.content|truncate(100) }}  {# Truncate to 100 chars #}
    
    • Preserves HTML tags (e.g., <p>, <a>) within the truncated text.
  2. Custom Separators:

    {{ text|truncate(50, ' [read more]') }}
    
    • Replace ... with a custom suffix (e.g., for "Read More" links).
  3. Absolute vs. Relative Truncation:

    {{ text|truncate(50, '', true) }}  {# Absolute truncation (no partial words) #}
    
  4. Integration with Forms/Entities:

    • Use in Twig templates for previewing truncated content (e.g., in admin panels or search results):
      <div class="preview">{{ post.excerpt|truncate(80) }}</div>
      
  5. Dynamic Truncation Length:

    • Pass a variable from PHP to Twig:
      return $this->render('template.html.twig', [
          'truncateLength' => $user->preferredLength ?? 100,
      ]);
      
      {{ text|truncate(truncateLength) }}
      

Advanced Patterns

  1. Combining with Other Filters:

    {{ text|striptags|truncate(30)|upper }}
    
    • Strip HTML first, then truncate and uppercase.
  2. Conditional Truncation:

    {% if showFullText %}
        {{ text }}
    {% else %}
        {{ text|truncate(150) }}
    {% endif %}
    
  3. Reusable Macros: Define a macro in Twig for consistent truncation:

    {% macro truncateText(text, length=100) %}
        {{ text|truncate(length, '...') }}
    {% endmacro %}
    

    Usage:

    {{ _self.truncateText(article.body, 200) }}
    

Gotchas and Tips

Pitfalls

  1. Bundle Auto-Loading:

    • In Symfony 4+, the bundle should auto-enable, but if Twig filters aren’t working, manually add it to config/bundles.php:
      Dzango\Bundle\TwigTruncateBundle\TwigTruncateBundle::class => ['all' => true],
      
  2. HTML Tag Preservation Limits:

    • The extension preserves open tags but may break if truncation splits a tag (e.g., <a href="... mid-truncate). Test edge cases like:
      {{ '<a href="very-long-url-here">Click</a>'|truncate(10) }}
      
      Output: <a href="very-lo... (may render invalid HTML).
  3. Caching Issues:

    • If Twig filters stop working after clearing cache, run:
      php bin/console cache:clear
      
  4. Deprecated Symfony Versions:

    • The bundle was last updated in 2020 and may not support Symfony 6+. Test thoroughly if using newer versions.

Debugging Tips

  1. Verify Extension Registration:

    • Check if the extension is loaded in Twig:
      php bin/console debug:container dzango_twig_truncate
      
    • Should return the TwigTruncateExtension class.
  2. Test Edge Cases:

    • Empty strings: {{ ''|truncate(10) }} → Returns empty string.
    • Strings shorter than the limit: {{ 'short'|truncate(10) }} → Returns original.
  3. Custom Logic:

    • Override the extension by creating a custom Twig extension that extends TwigTruncateExtension and register it as a compiler pass.

Configuration Quirks

  1. No Config File:

    • The bundle has no YAML/PHP config; all settings are passed via Twig filters.
  2. Performance:

    • Truncation is lightweight, but avoid calling it in loops for large datasets (e.g., {% for item in hugeList %}{{ item.text|truncate }}...{% endfor %}). Cache truncated results if needed.

Extension Points

  1. Custom Truncation Logic:

    • Extend the extension by creating a new Twig extension:
      use Dzango\TwigTruncateExtension\TwigTruncateExtension as BaseExtension;
      
      class CustomTruncateExtension extends BaseExtension {
          public function getFunctions() {
              return array_merge(parent::getFunctions(), [
                  new \Twig\TwigFunction('customTruncate', [$this, 'customTruncate']),
              ]);
          }
      
          public function customTruncate($text, $length, $suffix = '...') {
              // Custom logic here
              return parent::truncate($text, $length, $suffix);
          }
      }
      
    • Register it in services.yaml:
      services:
          App\Twig\CustomTruncateExtension:
              tags: ['twig.extension']
      
  2. Integration with API Platform:

    • Use in serializers for truncated previews:
      use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
      
      class ArticleOutput {
          #[Groups(['default'])]
          public string $contentPreview;
      
          public function __construct(string $content) {
              $this->contentPreview = $content;
          }
      }
      
      // In your controller:
      $preview = $article->content|truncate(150); // Hypothetical; use a custom serializer method.
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle