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

core23/twig-formatter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Prerequisites: Ensure you have sonata-project/formatter-bundle installed (composer require sonata-project/formatter-bundle).
  2. Install the Bundle:
    composer require core23/twig-formatter-bundle
    
  3. Enable the Bundle: Add to config/bundles.php:
    return [
        // ...
        Core23\TwigFormatterBundle\Core23TwigFormatterBundle::class => ['all' => true],
    ];
    
  4. Configure Twig: Ensure Twig is registered in your config/packages/twig.yaml:
    twig:
        form_themes: ['@Core23TwigFormatter/formatter.html.twig']
    

First Use Case

Render a formatted text block in Twig:

{{ sonata_formatter_block({
    content: 'This is **bold** and this is *italic*',
    format: 'html'
}) }}
  • Key: The bundle extends Sonata’s formatter functionality to Twig, allowing seamless integration of rich-text formatting.

Implementation Patterns

Core Workflows

  1. Twig Integration:

    • Use sonata_formatter_block in Twig templates to render formatted content.
    • Pass content (string) and format (e.g., 'html', 'text') as parameters.
    • Example:
      {% set formattedContent = sonata_formatter_block({
          content: node.content,
          format: node.format
      }) %}
      
  2. Dynamic Formatting:

    • Fetch formatted content from Doctrine entities (e.g., Article with content and format fields):
      {{ sonata_formatter_block({
          content: article.content,
          format: article.format,
          settings: sonata_formatter.settings
      }) }}
      
  3. Custom Settings:

    • Override default formatter settings via Twig:
      {{ sonata_formatter_block({
          content: rawText,
          format: 'html',
          settings: {
              'extra': {
                  'allowed_tags': ['b', 'i', 'a']
              }
          }
      }) }}
      

Integration Tips

  • Symfony Forms: Use with Sonata Admin for rich-text fields:
    {{ form_row(form.content, {
        'attr': {
            'data-sonata-formatter': 'true',
            'data-sonata-formatter-format': 'html'
        }
    }) }}
    
  • API Responses: Serialize formatted content in controllers:
    return $this->json([
        'content' => $formatter->getContent($entity->content, $entity->format)
    ]);
    
  • Caching: Cache formatted output in Twig:
    {% cache 'formatted_content_' ~ article.id %}
        {{ sonata_formatter_block({...}) }}
    {% endcache %}
    

Gotchas and Tips

Pitfalls

  1. Missing Dependencies:

    • Error: Twig\Error\RuntimeError: "sonata_formatter_block" is not defined.
    • Fix: Ensure sonata-project/formatter-bundle is installed and the bundle is enabled.
  2. Format Mismatch:

    • Error: Formatted content renders as plain text.
    • Fix: Verify the format parameter matches the stored format (e.g., 'html' vs 'text').
  3. Twig Configuration:

    • Error: TemplateNotFoundException for @Core23TwigFormatter/formatter.html.twig.
    • Fix: Confirm the bundle is enabled and Twig is configured to load the theme.

Debugging

  • Log Settings: Dump formatter settings for debugging:
    {{ dump(sonata_formatter.settings) }}
    
  • Raw Content Fallback: Use {{ content|raw }} if formatting fails, but sanitize input first.

Extension Points

  1. Custom Formatters:

    • Extend the bundle by creating a custom formatter service and registering it with Sonata’s formatter registry.
  2. Twig Filters:

    • Create a custom Twig filter for formatted content:
      // src/Twig/AppExtension.php
      public function getFilters()
      {
          return [
              new \Twig\TwigFilter('format_content', [$this->formatter, 'getContent'])
          ];
      }
      
      Usage:
      {{ article.content|format_content(article.format) }}
      
  3. Configuration Overrides:

    • Override default settings in config/packages/core23_twig_formatter.yaml:
      core23_twig_formatter:
          settings:
              'extra':
                  'allowed_tags': ['b', 'i', 'u', 'em', 'strong']
      

Pro Tips

  • Performance: Use {{ sonata_formatter_block({...})|striptags }} to strip HTML tags if needed.
  • Security: Always validate format and content in controllers before passing to Twig.
  • Testing: Mock the formatter in PHPUnit:
    $formatter = $this->createMock(\Sonata\FormatterBundle\Formatter\FormatterInterface::class);
    $this->container->set('sonata.formatter.pool', $this->createMock(\Sonata\FormatterBundle\Formatter\Pool::class));
    
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.
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle