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

Translation Bundle Laravel Package

adcog-cpi/translation-bundle

Symfony bundle providing translation-aware link helpers for controllers and Twig. Generates tags with translated name/title/description from route keys, optional route-to-class, underscore-to-dot mapping, prefixing, and active-route tracking via configurable defaults.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adcog-cpi/translation-bundle
    

    Add the bundle to AppKernel.php (or config/bundles.php for Symfony 4+):

    new EB\TranslationBundle\TranslationBundle(),
    
  2. Configure Update config/packages/eb_translation.yaml (or app/config/config.yml for Symfony <4):

    eb_translation:
        domain: messages
        locale: '%kernel.default_locale%'
        use_route_as_class: false
        replace_underscore: true
        prefix: 'page.'
        track_selected_links: 'active'
    
  3. First Use Case Define translations in translations/messages.fr.yml:

    page:
        home:
            name: 'Accueil'
            title: 'Page d''accueil'
    

    Generate a link in a Twig template:

    {{ translation.link('home') }}
    

    Output:

    <a href="/" title="Page d'accueil">Accueil</a>
    

Implementation Patterns

Core Workflows

  1. Link Generation

    • Basic Route Linking:
      {{ translation.link('route_name') }}
      
    • Dynamic Parameters:
      {{ translation.link('route_name', {'param': 'value'}) }}
      
    • Custom Text/Title:
      {{ translation.link('route_name', {}, {'name': 'Custom Text', 'title': 'Custom Title'}) }}
      
  2. Controller Integration Inject the service and use it programmatically:

    public function index(Translation $translation) {
        return $translation->link('home', ['page' => 1], ['class' => 'btn']);
    }
    
  3. Translation Structure

    • Nested Routes:
      page:
          admin:
              users:
                  name: 'Users'
                  title: 'User Management'
      
      Access via admin_users (if replace_underscore: true).
  4. Active Link Tracking Automatically adds active class if track_selected_links is enabled:

    {{ translation.link('current_route') }} <!-- Will include 'active' class -->
    
  5. Custom Prefixes Override the prefix to organize translations:

    eb_translation:
        prefix: 'custom.'
    
    custom:
        home:
            name: 'Home'
    

Integration Tips

  • Twig Extensions Use the translation Twig function globally by adding to twig/config.yaml:

    twig:
        globals:
            translation: '@eb_translation'
    
  • Dynamic Locale Switching Change locale dynamically in controllers:

    $translation->setLocale('en');
    
  • Route Name Conversion Leverage replace_underscore for cleaner YAML:

    page:
        home_index:  # Maps to 'home.index' in translations
            name: 'Home'
    
  • Custom Link Attributes Pass additional HTML attributes:

    {{ translation.link('home', {}, {'class': 'btn-primary', 'data-toggle': 'modal'}) }}
    

Gotchas and Tips

Pitfalls

  1. Route Name Mismatches

    • If replace_underscore: true, ensure route names in translations match the converted format (e.g., home_indexhome.index).
    • Fix: Verify route names with php bin/console debug:router and adjust translations accordingly.
  2. Missing Translations

    • If a translation key is missing, the link will render with the route name as text.
    • Fix: Add a fallback in YAML or handle missing keys in PHP:
      $translation->link('missing_route', [], ['name' => 'Fallback Text']);
      
  3. Locale Configuration

    • %locale% or %kernel.default_locale% must resolve correctly. Test with:
      $this->getParameter('locale'); // Verify in a controller
      
  4. Caching Issues

    • Translations are cached. Clear cache after updates:
      php bin/console cache:clear
      
  5. Route Overrides

    • If routes change but translations remain, links may break.
    • Fix: Use use_route_as_class: true to dynamically generate classes based on route names.

Debugging Tips

  1. Check Generated HTML Temporarily add {{ dump(translation.link('route_name')) }} to inspect output.

  2. Validate Route Names Use Symfony’s router to debug:

    php bin/console debug:router | grep "route_name"
    
  3. Translation Dumping Dump loaded translations for debugging:

    $translator = $this->get('translator');
    dump($translator->getCatalogue()->get('messages', 'fr')->all());
    
  4. Override Default Behavior Extend the bundle’s service to customize logic:

    # config/services.yaml
    EB\TranslationBundle\Translation:
        arguments:
            $defaultOptions: ['custom_prefix' => 'app.']
    

Extension Points

  1. Custom Link Builders Extend the Translation service to add methods like:

    public function buttonLink(string $route, array $params = [], array $options = []): string
    {
        $options['class'] = 'btn ' . ($options['class'] ?? '');
        return $this->link($route, $params, $options);
    }
    
  2. Dynamic Prefixes Override the prefix per request:

    $translation->setPrefix('dynamic.');
    
  3. Post-Process Link HTML Subscribe to the eb_translation.link.html event to modify output:

    $eventDispatcher->addListener('eb_translation.link.html', function (LinkEvent $event) {
        $event->setHtml(str_replace('href', 'data-href', $event->getHtml()));
    });
    
  4. Fallback Translations Implement a fallback chain in the service:

    public function getTranslation(string $key, string $locale): string
    {
        $translation = $this->translator->trans($key, [], null, $this->domain, $locale);
        return $translation ?: $this->getFallbackTranslation($key, $locale);
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor