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

Js Translation Bundle Laravel Package

willdurand/js-translation-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require willdurand/js-translation-bundle

Add to config/bundles.php:

return [
    // ...
    WillDurand\JsTranslationBundle\WillDurandJsTranslationBundle::class => ['all' => true],
];
  1. Configuration: Publish the default config:

    php bin/console config:dump-reference WillDurandJsTranslationBundle
    

    Or customize in config/packages/willdurand_js_translation.yaml:

    willdurand_js_translation:
        output_path: '%kernel.project_dir%/public/js/translations'
        domains: ['messages', 'validators']
        json_encode_options: 0
        jsonp_callback: null
        ignore_patterns: ['%kernel.project_dir%/vendor']
        include_original_values: false
    
  2. First Use Case: Dump translations to JS:

    php bin/console assets:install public/
    php bin/console willdurand:js-translation:dump
    

    This generates a translations.js file in public/js/translations/ with all translation keys.

  3. Usage in JavaScript:

    // Load translations.js in your frontend (e.g., via asset pipeline)
    const translations = window.translations; // Access via global variable
    console.log(translations.messages.hello); // Output: "Hello!"
    

Implementation Patterns

Core Workflow

  1. Translation Dumping:

    • Run wildurand:js-translation:dump to generate translations.js with all loaded translation domains.
    • Schedule this task in a post-update or post-deploy hook (e.g., via Symfony’s CronBundle or Git hooks).
  2. Integration with Frontend:

    • Asset Pipeline: Include translations.js in your main JS bundle (e.g., Webpack Encore, Vite, or Laravel Mix):
      // webpack.mix.js
      mix.js('resources/js/app.js', 'public/js')
          .copy('public/js/translations.js', 'public/js/translations.js');
      
    • Dynamic Loading: For SPAs, fetch translations via AJAX:
      fetch('/js/translations.js')
          .then(response => response.text())
          .then(text => {
              const script = document.createElement('script');
              script.textContent = text;
              document.head.appendChild(script);
          });
      
  3. Domain-Specific Translations:

    • Configure domains in willdurand_js_translation.yaml to include only necessary domains (e.g., ['messages', 'validators']).
    • Access domain-specific translations in JS:
      console.log(translations.validators.required); // "This value should not be blank."
      
  4. Localization in Templates:

    • Use Symfony’s trans filter in Twig to ensure consistency:
      {{ 'hello'|trans({ '%name%': user.name }, 'messages') }}
      
    • The same keys will be available in JS.
  5. Parameterized Translations:

    • Pass parameters when dumping translations (e.g., for locale-specific values):
      php bin/console willdurand:js-translation:dump --locale=en --locale=fr
      
    • Access in JS:
      console.log(translations.messages.hello.name); // "Hello, %name%!"
      
  6. JSONP Support:

    • Enable JSONP for cross-domain requests:
      willdurand_js_translation:
          jsonp_callback: callback
      
    • Fetch in JS:
      const script = document.createElement('script');
      script.src = `/js/translations.js?callback=handleTranslations`;
      document.body.appendChild(script);
      
      function handleTranslations(data) {
          console.log(data.messages.hello);
      }
      

Advanced Patterns

  1. Custom Output Paths:

    • Override output_path to integrate with your asset pipeline:
      willdurand_js_translation:
          output_path: '%kernel.project_dir%/public/build/assets/translations'
      
  2. Excluding Vendor Translations:

    • Use ignore_patterns to exclude third-party translations:
      willdurand_js_translation:
          ignore_patterns: ['%kernel.project_dir%/vendor/*', '%kernel.project_dir%/node_modules/*']
      
  3. Translation Namespaces:

    • Organize translations by namespace in your .po/.yml files:
      messages:
          auth:
              login: "Login"
      
    • Access in JS:
      console.log(translations.messages.auth.login);
      
  4. Dynamic Locale Switching:

    • Dump translations for multiple locales and switch dynamically:
      // Load translations for the current locale
      fetch(`/js/translations_${currentLocale}.js`)
          .then(response => response.text())
          .then(text => {
              const script = document.createElement('script');
              script.textContent = text;
              document.head.appendChild(script);
          });
      
  5. Integration with Frontend Frameworks:

    • Vue/React: Bind translations to Vuex/Redux stores or React context:
      // Vue example
      export default {
          data() {
              return {
                  translations: window.translations.messages
              };
          }
      };
      
    • i18next: Use the bundle as a source for i18next:
      i18next.init({
          resources: {
              en: { translation: window.translations.messages }
          }
      });
      
  6. Translation Updates Without Full Reload:

    • Use a versioned filename (e.g., translations_v2.js) and cache-busting:
      willdurand_js_translation:
          output_path: '%kernel.project_dir%/public/js/translations_v{{ date("YmdHis") }}.js'
      
    • Or append a hash to the filename in your asset pipeline.

Gotchas and Tips

Common Pitfalls

  1. Translation Keys Mismatch:

    • Issue: Keys in JS don’t match those in Twig/PHP.
    • Fix: Ensure consistent key naming across all translation files (.po, .yml, .xliff). Use the same domain and namespace.
    • Debug: Compare keys in translations.js with those used in {{ 'key'|trans }} in Twig.
  2. Locale-Specific Files:

    • Issue: Translations are dumped for en only, even though other locales are configured.
    • Fix: Explicitly specify locales when dumping:
      php bin/console willdurand:js-translation:dump --locale=en --locale=fr
      
    • Config: Ensure framework.default_locale in config/packages/framework.yaml matches your expected locale.
  3. Caching Issues:

    • Issue: Changes to translations aren’t reflected in JS.
    • Fix:
      • Clear cache after updating translations:
        php bin/console cache:clear
        
      • For production, use cache-busting (e.g., versioned filenames or query strings).
      • Ensure output_path is writable by the web server.
  4. JSONP Security:

    • Issue: JSONP requests are vulnerable to XSS if jsonp_callback is user-controlled.
    • Fix: Restrict jsonp_callback to a fixed value or disable it in production:
      willdurand_js_translation:
          jsonp_callback: null  # Disable JSONP in production
      
  5. Large Translation Files:

    • Issue: translations.js becomes too large, slowing down page loads.
    • Fix:
      • Split translations by domain or feature (e.g., auth.js, forms.js).
      • Use lazy loading for non-critical translations.
      • Compress the output with json_encode_options:
        willdurand_js_translation:
            json_encode_options: JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT
        
  6. Original Values Leak:

    • Issue: Original (non-translated) values are exposed in JS.
    • Fix: Enable include_original_values only for debugging:
      willdurand_js_translation:
          include_original_values: false  # Default
      
  7. Symfony 6+ Compatibility:

    • Issue: Bundle may not work out-of-the-box with Symfony 6’s autowiring or new config system.
    • Fix:
      • Ensure WillDurandJsTranslationBundle is listed in config/bundles.php.
      • Use the config/packages/ directory for configuration (Symfony 5+ style).
      • For Symfony 6, check for updated dependencies or forks.

Debugging Tips

  1. Verify Dumped Translations:
    • Check the generated translations.js file for expected keys:
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui