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

Translator Bundle Laravel Package

docteurklein/translator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require docteurklein/translator-bundle:dev-master
    

    (Note: Use dev-master as the last stable release is outdated.)

  2. Register the Bundle: Add to app/AppKernel.php:

    new Knp\Bundle\TranslatorBundle\KnpTranslatorBundle(),
    new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), // Required for DB storage
    
  3. Configure Translator:

    # app/config/config.yml
    framework:
        translator:
            fallbacks: ["%locale%"]
            paths:
                - "%kernel.project_dir%/app/Resources/translations"
            default_path: "%kernel.project_dir%/app/Resources/translations"
    
  4. Set Up Database (Optional but recommended): Run migrations:

    php app/console doctrine:schema:update --force
    
  5. Enable Routes: Add to app/config/routing.yml:

    knp_translator_admin:
        resource: "@KnpTranslatorBundle/Resources/config/routing/edition.yml"
        prefix: /admin/translations
    

First Use Case

  • Access the UI: Navigate to /admin/translations to manage translations via a web interface.
  • Add a Translation:
    1. Click "Add Translation" in the UI.
    2. Select a domain (e.g., messages).
    3. Enter a locale (e.g., en or fr).
    4. Add a key (e.g., welcome.message) and its translation.
    5. Save.

Implementation Patterns

Workflows

  1. Localization Workflow:

    • Developers: Use the UI to add/translate keys during feature development.
    • Translators: Non-technical users can edit translations via the web interface without touching code.
    • Review: Use the "Compare" feature to review changes before merging.
  2. Integration with Forms: Dynamically load translations for form labels/placeholders:

    {{ form_label(form.name, 'welcome.message'|trans({'%name%': user.name}, 'messages')) }}
    
  3. Domain-Specific Translations: Organize translations by domain (e.g., validation, emails) for modularity:

    # app/Resources/translations/messages.en.yml
    welcome:
        message: "Hello, %name%!"
    
  4. CLI Management: Use Symfony’s console for bulk operations:

    php app/console knp:translator:dump --format=yaml --dir=%kernel.project_dir%/app/Resources/translations
    

Integration Tips

  • Symfony Forms: Extend AbstractType to auto-load translations for form fields:

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('name', TextType::class, [
            'label' => $this->translator->trans('user.name', [], 'validation'),
        ]);
    }
    
  • Twig Extensions: Create a custom Twig extension to shorten translation calls:

    // src/AppBundle/Twig/AppExtension.php
    public function getFunctions() {
        return [
            new \Twig\TwigFunction('t', [$this->translator, 'trans']),
        ];
    }
    

    Usage in Twig:

    {{ t('welcome.message', {'%name%': user.name}, 'messages') }}
    
  • Event Listeners: Trigger actions on translation updates (e.g., cache invalidation):

    // src/AppBundle/EventListener/TranslationListener.php
    public function onTranslationUpdate(TranslationEvent $event) {
        $this->cache->delete('translations');
    }
    

Gotchas and Tips

Pitfalls

  1. Outdated Documentation:

    • The bundle’s last release is from 2015. Refer to the KnpLabs fork for modern usage.
    • Example: The edition.yml routing may differ; check the actual bundle files.
  2. Database Dependency:

    • The bundle requires Doctrine for storage. If you don’t need persistence, configure it to use files only:
      knp_translator:
          file:
              dir: "%kernel.project_dir%/app/Resources/translations"
      
  3. Locale Fallbacks:

    • Misconfigured fallbacks can break translations. Ensure fallbacks in config.yml is an array:
      translator:
          fallbacks:
              - "%locale%"
              - en
      
  4. Route Conflicts:

    • The /trans prefix may clash with other bundles. Use a unique prefix like /i18n.
  5. CSV/XLIFF Support:

    • These formats require additional setup. For CSV, ensure the file has headers matching the bundle’s expectations (e.g., id, message, locale).

Debugging

  • Missing Translations:

    • Check if the domain/locale exists in the UI or via CLI:
      php app/console knp:translator:list
      
    • Verify the translation file is in the correct directory and has the right format (YAML/CSV/XLIFF).
  • UI Not Loading:

    • Ensure Doctrine is properly configured and the database schema is updated.
    • Clear cache:
      php app/console cache:clear
      
  • Permission Issues:

    • The UI requires ROLE_ADMIN by default. Adjust security in security.yml if needed:
      access_control:
          - { path: ^/admin/translations, roles: ROLE_TRANSLATOR }
      

Tips

  1. Backup Translations:

    • Regularly dump translations to version control:
      php app/console knp:translator:dump --format=yaml --dir=backups/translations
      
  2. Custom Domains:

    • Dynamically register domains in config.yml:
      knp_translator:
          domains:
              - { path: app/Resources/translations, default_locale: en }
              - { path: vendor/bundle/translations, default_locale: en }
      
  3. Translation Validation:

    • Use Symfony’s validator to ensure translations meet requirements (e.g., length):
      $translator->addValidator(function ($translation) {
          return strlen($translation['message']) > 10;
      });
      
  4. Performance:

    • For large projects, preload translations in a service:
      // src/AppBundle/Service/TranslationLoader.php
      public function __construct(TranslatorInterface $translator) {
          $this->translator = $translator;
          $this->translator->setFallbackLocales(['en']);
      }
      
  5. Testing:

    • Mock the translator in tests to avoid file/database dependencies:
      $translator = $this->createMock(TranslatorInterface::class);
      $translator->method('trans')->willReturn('Mocked translation');
      $this->container->set('translator', $translator);
      
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.
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
leek/filament-subtenant-scope