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

darkcat/twig-translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require darkcat/twig-translation-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Darkcat\TwigTranslationBundle\DarkcatTwigTranslationBundle::class => ['all' => true],
    ];
    
  2. 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'
    
  3. First Use Case

    • Deploy to en.example.com and fr.example.com with identical codebases.
    • Replace {{ 'Hello'|trans }} in Twig templates. The bundle automatically translates during cache generation (no runtime overhead).

Implementation Patterns

Workflow Integration

  1. Locale Routing Use Symfony’s LocaleListener to set the locale via subdomains:

    # config/routes.yaml
    _locale:
        resource: "@DarkcatTwigTranslationBundle/Resources/config/routing/locale.yaml"
    
  2. Translation Files Place translations in translations/messages.{locale}.yaml (standard Symfony format):

    # translations/messages.fr.yaml
    "Hello": Bonjour
    
  3. Cache Warmup Run during deploy to pre-generate locale-specific Twig caches:

    php bin/console cache:warmup --env=prod --no-debug
    
  4. 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
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Cache Invalidation

    • Clear Twig cache per locale after translation updates:
      php bin/console cache:clear --env=prod --no-debug --locale=fr
      
    • Use cache:pool:clear twig for granular control.
  2. Domain-Locale Mismatch

    • Ensure RequestContext in Symfony matches the subdomain (e.g., fr.example.comfr locale).
    • Debug with:
      dump($this->get('request_stack')->getCurrentRequest()->getLocale());
      
  3. Dynamic Content

    • Avoid dynamic translations (e.g., {{ user.name|trans }}). Use strtr for runtime replacements:
      {{ 'Welcome %name%'|trans({'%name%': user.name}) }}
      

Debugging

  • Check Cache Contents Inspect generated Twig files in var/cache/twig/ for plaintext output (no trans calls).
  • Enable Debug Mode Temporarily set debug: true in config/packages/darkcat_twig_translation.yaml to log translation events.

Extension Points

  1. Custom Loaders Override Darkcat\TwigTranslationBundle\Loader\TranslationLoader to integrate with APIs or databases.
  2. Event Listeners Subscribe to Darkcat\TwigTranslationBundle\Event\TranslateEvent for pre/post-translation logic.
  3. Twig Extensions Add custom filters to the bundle’s DarkcatTwigTranslationExtension:
    // src/Twig/DarkcatCustomExtension.php
    class DarkcatCustomExtension extends \Twig\Extension\AbstractExtension {
        public function getFilters() {
            return [
                new \Twig\TwigFilter('custom_trans', [$this, 'customTranslate']),
            ];
        }
    }
    

Performance Notes

  • Benchmark: Compare time bin/console cache:warmup before/after bundle usage.
  • Exclude Non-Translated Templates: Use {% trans_default %} blocks for static content:
    {% trans_default %}
        This text is cached as-is.
    {% endtrans_default %}
    
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.
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament