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 Extensions Laravel Package

core23/twig-extensions

Extra Twig extensions and helpers for PHP apps, packaged as a lightweight bundle. Adds convenient filters, functions, and runtime utilities to simplify templates and reduce boilerplate, with straightforward integration into existing Twig environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer in your Laravel project:

    composer require core23/twig-extensions
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Core23\TwigExtensions\TwigExtensionsServiceProvider::class,
    ],
    
  2. Basic Usage Ensure Twig is configured in Laravel (e.g., via spatie/laravel-twig). Then, leverage the extensions in your Twig templates:

    {{ "hello world"|uppercase }}  {# Outputs: HELLO WORLD #}
    
  3. First Use Case Use the date filter to format dates elegantly:

    {{ now()|date('Y-m-d') }}  {# Outputs current date in YYYY-MM-DD format #}
    

Implementation Patterns

Common Workflows

  1. String Manipulation Chain filters for concise transformations:

    {{ "  example  " | trim | title | replace({' ': '-'}) }}
    {# Outputs: "Example" #}
    
  2. Conditional Rendering Use if with custom filters for dynamic logic:

    {% if user.isAdmin() %}
        {{ "Admin Panel"|highlight("Admin") }}
    {% endif %}
    
  3. Loop Enhancements Add indices or keys to loops:

    {% for item in items %}
        {{ loop.index }}. {{ item.name }}
    {% endfor %}
    
  4. JSON Handling Pretty-print JSON in templates:

    {{ json_encode(data) | json_pretty }}
    

Integration Tips

  • Laravel Blade Compatibility: Use Twig inside Blade via {{ Twig\... }} or embed Twig templates.
  • Custom Extensions: Extend the package by creating a custom Twig extension:
    use Core23\TwigExtensions\TwigExtensionsServiceProvider;
    class CustomTwigExtensionsServiceProvider extends TwigExtensionsServiceProvider {
        public function registerExtensions() {
            $this->twig->addExtension(new \Custom\Twig\Extension());
        }
    }
    
  • Caching: Enable Twig cache in config/twig.php for performance:
    'cache' => env('APP_ENV') !== 'production' ? false : storage_path('framework/views'),
    

Gotchas and Tips

Pitfalls

  1. Filter Conflicts Avoid naming custom filters the same as built-in Twig/this package’s filters (e.g., date). Prefix them:

    {{ now()|myapp_date('custom_format') }}
    
  2. Performance with Loops Heavy loops with loop filters (e.g., loop.index, loop.length) can slow rendering. Cache results if used frequently:

    {% set loopData = loop %}
    {% for item in items %}
        {{ loopData.index }}. {{ item.name }}
    {% endfor %}
    
  3. JSON Security The json_encode filter escapes output by default. Use |raw cautiously:

    {{ json_encode(data)|raw }}  {# Only if data is trusted #}
    

Debugging

  • Filter Not Working? Verify the extension is registered. Check bootstrap/cache/services.php for the provider.

    php artisan config:clear
    php artisan cache:clear
    
  • Twig Errors Enable Twig’s debug mode in config/twig.php:

    'debug' => env('APP_DEBUG', false),
    

Extension Points

  1. Custom Filters Add filters via a service provider:

    $this->twig->addFilter(new \Twig\TwigFilter('custom_filter', function ($str) {
        return strtoupper($str);
    }));
    
  2. Global Variables Pass data to all Twig templates:

    TwigExtensionsServiceProvider::booting(function () {
        $twig = app('twig');
        $twig->addGlobal('app_name', config('app.name'));
    });
    
  3. Override Existing Filters Replace default filters (e.g., date) by re-registering them with custom logic:

    $this->twig->addFilter(new \Twig\TwigFilter('date', function ($date, $format) {
        return Carbon::parse($date)->format($format);
    }));
    
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