core23/twig-formatter-bundle
sonata-project/formatter-bundle installed (composer require sonata-project/formatter-bundle).composer require core23/twig-formatter-bundle
config/bundles.php:
return [
// ...
Core23\TwigFormatterBundle\Core23TwigFormatterBundle::class => ['all' => true],
];
config/packages/twig.yaml:
twig:
form_themes: ['@Core23TwigFormatter/formatter.html.twig']
Render a formatted text block in Twig:
{{ sonata_formatter_block({
content: 'This is **bold** and this is *italic*',
format: 'html'
}) }}
Twig Integration:
sonata_formatter_block in Twig templates to render formatted content.content (string) and format (e.g., 'html', 'text') as parameters.{% set formattedContent = sonata_formatter_block({
content: node.content,
format: node.format
}) %}
Dynamic Formatting:
Article with content and format fields):
{{ sonata_formatter_block({
content: article.content,
format: article.format,
settings: sonata_formatter.settings
}) }}
Custom Settings:
{{ sonata_formatter_block({
content: rawText,
format: 'html',
settings: {
'extra': {
'allowed_tags': ['b', 'i', 'a']
}
}
}) }}
{{ form_row(form.content, {
'attr': {
'data-sonata-formatter': 'true',
'data-sonata-formatter-format': 'html'
}
}) }}
return $this->json([
'content' => $formatter->getContent($entity->content, $entity->format)
]);
{% cache 'formatted_content_' ~ article.id %}
{{ sonata_formatter_block({...}) }}
{% endcache %}
Missing Dependencies:
Twig\Error\RuntimeError: "sonata_formatter_block" is not defined.sonata-project/formatter-bundle is installed and the bundle is enabled.Format Mismatch:
format parameter matches the stored format (e.g., 'html' vs 'text').Twig Configuration:
TemplateNotFoundException for @Core23TwigFormatter/formatter.html.twig.{{ dump(sonata_formatter.settings) }}
{{ content|raw }} if formatting fails, but sanitize input first.Custom Formatters:
Twig Filters:
// src/Twig/AppExtension.php
public function getFilters()
{
return [
new \Twig\TwigFilter('format_content', [$this->formatter, 'getContent'])
];
}
Usage:
{{ article.content|format_content(article.format) }}
Configuration Overrides:
config/packages/core23_twig_formatter.yaml:
core23_twig_formatter:
settings:
'extra':
'allowed_tags': ['b', 'i', 'u', 'em', 'strong']
{{ sonata_formatter_block({...})|striptags }} to strip HTML tags if needed.format and content in controllers before passing to Twig.$formatter = $this->createMock(\Sonata\FormatterBundle\Formatter\FormatterInterface::class);
$this->container->set('sonata.formatter.pool', $this->createMock(\Sonata\FormatterBundle\Formatter\Pool::class));
How can I help you explore Laravel packages today?