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

Apply Filter Twig Extension Bundle Laravel Package

danilovl/apply-filter-twig-extension-bundle

Symfony Twig bundle that adds an apply_filter() function to call Twig filters dynamically from templates. Choose filter names at runtime and apply them to values (e.g., upper/lower/max), enabling flexible rendering logic.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require danilovl/apply-filter-twig-extension-bundle
    

    Ensure Danilovl\ApplyFilterTwigExtensionBundle\ApplyFilterTwigExtensionBundle::class is registered in config/bundles.php.

  2. First Use Case: Apply a built-in PHP filter dynamically in Twig:

    {{ apply_filter('upper', 'hello') }}  {# Outputs: HELLO #}
    

    Test with common filters like lower, trim, ucfirst, or json_encode.

Where to Look First

  • Tests: The tests/ directory contains practical examples of filter usage.
  • Bundle Docs: Check src/DependencyInjection/ for configuration options (if any).
  • Twig Docs: Review Symfony’s Twig documentation for supported filters.

Implementation Patterns

Dynamic Filter Application

Use apply_filter to chain or conditionally apply filters:

{% set text = '  hello world  ' %}
{{ apply_filter('trim', apply_filter('lower', text)) }}  {# Outputs: hello world #}

Conditional Filter Logic

Leverage Twig’s control structures:

{% set filter = isAdmin ? 'upper' : 'lower' %}
{{ apply_filter(filter, 'test') }}

Custom Filter Integration

Extend the bundle by registering custom PHP filters in your Twig environment:

// src/Twig/AppExtension.php
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('custom_filter', [$this, 'customFilter']),
        ];
    }

    public function customFilter(string $input): string
    {
        return strrev($input); // Example: reverse string
    }
}

Then use it in Twig:

{{ apply_filter('custom_filter', 'hello') }}  {# Outputs: olleh #}

Performance Considerations

  • Cache Filters: Precompute filter results in PHP when possible to avoid repeated Twig evaluations.
  • Avoid Overuse: Dynamic filters can impact rendering speed if overused in loops.

Gotchas and Tips

Pitfalls

  1. Filter Availability:

    • Only PHP’s built-in filters (e.g., strtolower, json_encode) work by default.
    • Custom filters require manual registration (see Custom Filter Integration above).
    • Debug Tip: Use {{ dump(apply_filter('filter_name', var)) }} to verify filter behavior.
  2. Error Handling:

    • Invalid filter names throw Twig\Error\RuntimeError. Validate dynamically passed filter names in PHP:
      if (!function_exists($filterName)) {
          throw new \RuntimeException("Filter '$filterName' not found.");
      }
      
  3. Security:

    • Sanitize dynamic filter inputs to prevent arbitrary code execution:
      {% set allowedFilters = ['upper', 'lower', 'trim'] %}
      {% if filterName in allowedFilters %}
          {{ apply_filter(filterName, text) }}
      {% endif %}
      

Debugging Tips

  • Check Filter Names: Ensure filter names match PHP’s exact function names (e.g., strtoupper vs. upper).
  • Twig Profiler: Use Symfony’s Twig profiler to inspect filter execution time:
    // config/packages/twig.yaml
    twig:
        debug: '%kernel.debug%'
        profiler: '%kernel.debug%'
    

Extension Points

  1. Override Default Filters: Subclass the bundle’s extension to modify or replace filters:

    // src/Twig/ApplyFilterExtension.php
    use Danilovl\ApplyFilterTwigExtensionBundle\Twig\ApplyFilterExtension as BaseExtension;
    
    class ApplyFilterExtension extends BaseExtension
    {
        protected function getFilters(): array
        {
            return array_merge(parent::getFilters(), [
                'custom' => [$this, 'customFilter'],
            ]);
        }
    }
    
  2. Add Filter Arguments: Extend the bundle to support filter arguments (e.g., apply_filter('substr', 'hello', 1, 2)):

    // Custom extension logic
    public function applyFilter(string $filter, mixed $var, array $args = []): mixed
    {
        if (is_callable($filter)) {
            return call_user_func_array($filter, array_merge([$var], $args));
        }
        // Fallback to default behavior
    }
    

Configuration Quirks

  • No Config File: The bundle has no config/packages/ file, meaning all behavior is runtime-driven.
  • Bundle Auto-Registration: Works with Symfony Flex; no manual AppKernel registration needed.
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
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