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

24hoursmedia/twig-extension-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require 24hoursmedia/twig-extension-bundle
    
  2. Register Bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):
    // Symfony 4+
    T4\Bundle\TwigExtensionBundle\T4TwigExtensionBundle::class => ['all' => true],
    
    // Symfony 3
    new T4\Bundle\TwigExtensionBundle\T4TwigExtensionBundle(),
    
  3. First Use Case: Use the Google Analytics extension to append UTM parameters to links in Twig templates:
    {{ 'https://example.com'|ga_link('source', 'campaign') }}
    
    Output: https://example.com?utm_source=source&utm_campaign=campaign

Implementation Patterns

Google Analytics Extension

  • Dynamic UTM Parameters: Add campaign tracking to links dynamically in Twig:

    <a href="{{ path('home')|ga_link('newsletter', 'summer2024') }}">Visit Home</a>
    
  • Custom Filters: Extend the ga_link filter for custom UTM keys:

    {{ 'https://example.com'|ga_link('custom_key', 'value', {'utm_medium': 'email'}) }}
    

    Output: https://example.com?utm_source=custom_key&utm_campaign=value&utm_medium=email

  • Integration with Routing: Combine with Symfony’s path() function for clean URLs:

    {{ path('product', {'id': 123})|ga_link('product_page', 'purchase') }}
    

Validator Extension

  • Form Validation in Twig: Validate data directly in templates (e.g., for AJAX forms):

    {% set errors = 'user.email'|validate %}
    {% if errors %}
      <ul>
        {% for error in errors %}
          <li>{{ error.message }}</li>
        {% endfor %}
      </ul>
    {% endif %}
    
  • Reusable Validation Logic: Create Twig macros for common validation patterns:

    {% macro validateField(field, errors) %}
      <div class="form-group {% if errors|length > 0 %}has-error{% endif %}">
        <label>{{ field.label }}</label>
        <input type="text" name="{{ field.name }}">
        {% if errors %}
          <div class="help-block">
            {% for error in errors %}
              {{ error.message }}<br>
            {% endfor %}
          </div>
        {% endif %}
      </div>
    {% endmacro %}
    

    Usage:

    {% set emailErrors = 'user.email'|validate %}
    {{ _self.validateField(userEmailField, emailErrors) }}
    
  • Custom Validation Constraints: Pass Symfony Constraint objects to the filter:

    {% set customConstraint = App\Validator\Constraints\CustomConstraint::class %}
    {% set errors = 'user.input'|validate(customConstraint) %}
    

Workflow Integration

  1. Frontend Validation: Use the validator filter in Twig to show errors without full form submission (e.g., for SPA-like behavior).
  2. Analytics Tracking: Automate UTM parameter generation in templates to ensure consistency across marketing campaigns.
  3. Testing: Mock the Twig extensions in PHPUnit for isolated template testing:
    $twig->addExtension(new \T4\Bundle\TwigExtensionBundle\Twig\Extension\GaExtension());
    $twig->addExtension(new \T4\Bundle\TwigExtensionBundle\Twig\Extension\ValidatorExtension());
    

Gotchas and Tips

Pitfalls

  1. Bundle Registration:

    • Symfony 4+: Forgetting to add the bundle to config/bundles.php will silently fail.
    • Symfony 3: Ensure AppKernel.php is updated and the bundle is loaded after the FrameworkBundle.
    • Fix: Verify the bundle is listed in ContainerAware services or debug with php bin/console debug:container | grep twig.extension.
  2. Validator Extension:

    • Dependency Injection: The validator requires a ValidatorInterface instance. If not autowired, configure it manually:
      # config/services.yaml
      T4\Bundle\TwigExtensionBundle\Twig\Extension\ValidatorExtension:
        arguments:
          - '@validator'
      
    • Circular Dependencies: Avoid injecting the validator directly into controllers if using this extension in templates (Symfony’s DI may complain).
  3. Google Analytics:

    • URL Encoding: The ga_link filter does not encode URLs. Manually encode if needed:
      {{ ('https://example.com/search?q=' ~ query)|e('UTF-8')|ga_link('search', 'query') }}
      
    • Duplicate Parameters: The filter appends UTM parameters without checking for duplicates. Use Twig’s merge filter to avoid conflicts:
      {{ ('https://example.com?utm_source=old'|split('&'))|merge({'utm_campaign': 'new'})|join('&') }}
      

Debugging

  1. Extension Availability: Check if extensions are registered in Twig:

    {{ dump(_twig.extensions) }}
    

    Look for T4\Bundle\TwigExtensionBundle\Twig\Extension\*.

  2. Validator Errors: If validation fails silently, enable Symfony’s validator debug mode:

    # config/packages/validator.yaml
    validator:
        debug: true
    
  3. Twig Error Suppression: Wrap extensions in try-catch blocks to avoid template crashes:

    {% try %}
      {{ 'invalid.data'|validate }}
    {% catch Exception %}
      <p>Validation failed gracefully.</p>
    {% endtry %}
    

Tips

  1. Custom Extensions: Extend the bundle by creating your own Twig extensions and register them alongside:

    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFilters()
        {
            return [
                new \Twig\TwigFilter('custom_filter', [$this, 'customFilter']),
            ];
        }
    }
    

    Register in config/services.yaml:

    Twig\Extension\AppExtension: ~
    
  2. Configuration: Override default UTM parameters in config/packages/t4_twig_extension.yaml:

    t4_twig_extension:
        ga:
            default_parameters:
                utm_medium: 'website'
                utm_content: 'twig-generated'
    
  3. Performance: Cache compiled Twig templates with the extensions enabled to avoid reprocessing:

    # config/packages/twig.yaml
    twig:
        cache: '%kernel.cache_dir%/twig'
    
  4. Documentation: Refer to the GA Extension Docs and Validator Extension Docs for advanced use cases (e.g., custom validators or UTM parameter overrides).

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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