darkcat/twig-translation-bundle
Installation
composer require darkcat/twig-translation-bundle
Add to config/bundles.php:
return [
// ...
Darkcat\TwigTranslationBundle\DarkcatTwigTranslationBundle::class => ['all' => true],
];
Configuration
Override config/packages/darkcat_twig_translation.yaml:
darkcat_twig_translation:
locales: ['en', 'fr'] # Match your domains (e.g., en.example.com)
default_locale: 'en'
cache_dir: '%kernel.project_dir%/var/cache/twig'
First Use Case
en.example.com and fr.example.com with identical codebases.{{ 'Hello'|trans }} in Twig templates. The bundle automatically translates during cache generation (no runtime overhead).Locale Routing
Use Symfony’s LocaleListener to set the locale via subdomains:
# config/routes.yaml
_locale:
resource: "@DarkcatTwigTranslationBundle/Resources/config/routing/locale.yaml"
Translation Files
Place translations in translations/messages.{locale}.yaml (standard Symfony format):
# translations/messages.fr.yaml
"Hello": Bonjour
Cache Warmup Run during deploy to pre-generate locale-specific Twig caches:
php bin/console cache:warmup --env=prod --no-debug
Fallback Logic
Extend the bundle’s TranslationLoader to handle missing keys:
// src/EventSubscriber/TranslationSubscriber.php
use Darkcat\TwigTranslationBundle\Event\TranslateEvent;
public function onTranslate(TranslateEvent $event) {
if (!$event->hasTranslation()) {
$event->setTranslation($event->getId()); // Fallback to key
}
}
Cache Invalidation
php bin/console cache:clear --env=prod --no-debug --locale=fr
cache:pool:clear twig for granular control.Domain-Locale Mismatch
RequestContext in Symfony matches the subdomain (e.g., fr.example.com → fr locale).dump($this->get('request_stack')->getCurrentRequest()->getLocale());
Dynamic Content
{{ user.name|trans }}). Use strtr for runtime replacements:
{{ 'Welcome %name%'|trans({'%name%': user.name}) }}
var/cache/twig/ for plaintext output (no trans calls).debug: true in config/packages/darkcat_twig_translation.yaml to log translation events.Darkcat\TwigTranslationBundle\Loader\TranslationLoader to integrate with APIs or databases.Darkcat\TwigTranslationBundle\Event\TranslateEvent for pre/post-translation logic.DarkcatTwigTranslationExtension:
// src/Twig/DarkcatCustomExtension.php
class DarkcatCustomExtension extends \Twig\Extension\AbstractExtension {
public function getFilters() {
return [
new \Twig\TwigFilter('custom_trans', [$this, 'customTranslate']),
];
}
}
time bin/console cache:warmup before/after bundle usage.{% trans_default %} blocks for static content:
{% trans_default %}
This text is cached as-is.
{% endtrans_default %}
How can I help you explore Laravel packages today?