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

Extensions Laravel Package

twig/extensions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

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

    composer require twig/extensions
    

    Register the extensions in your Twig environment (typically in app/Providers/AppServiceProvider.php):

    use Twig\Extra\Markdown\MarkdownExtension;
    use Twig\Extra\String\StringExtension;
    use Twig\Extra\Markdown\Markdown;
    
    public function register()
    {
        $this->app->make(\Twig\Environment::class)->addExtension(new MarkdownExtension(new Markdown()));
        $this->app->make(\Twig\Environment::class)->addExtension(new StringExtension());
        // Add other extensions as needed
    }
    
  2. First Use Case Use the StringExtension for common string manipulations in your Twig templates:

    {{ 'hello world'|upper }}
    {{ 'Laravel'|title }}
    {{ '123.456'|number_format(2) }}
    
  3. Where to Look First

    • Documentation: Twig Extensions Docs (official docs for core Twig, but most extensions are well-documented).
    • Source Code: Browse the GitHub repository for specific extension implementations.
    • Laravel Integration: Check vendor/twig/extensions/src/ for extension classes and their methods.

Implementation Patterns

Common Workflows

  1. String Manipulations Leverage StringExtension for common tasks like:

    {{ 'example@test.com'|email }}
    {{ '2023-10-01'|date('Y-m-d H:i') }}
    {{ 'Laravel'|replace({'Laravel': 'Symfony'}) }}
    
  2. Markdown Support Use MarkdownExtension to render Markdown in templates:

    {{ '# Hello World\n\nThis is **Markdown**.'|markdown }}
    

    Configure the Markdown parser (e.g., parsedown or parsedown-extra) in your AppServiceProvider:

    $this->app->make(\Twig\Environment::class)->addExtension(
        new MarkdownExtension(new \ParsedownExtra())
    );
    
  3. Text and Intl Extensions Use TextExtension for pluralization and IntlExtension for locale-aware formatting:

    {% for i in 1..5 %}
        {{ i }} {{ 'item'|pluralize(i) }}
    {% endfor %}
    
    {{ 1234.56|number_format(2, '.', ',') }}
    
  4. Debugging and Profiler Enable DebugExtension for template debugging (useful in development):

    {% debug %}
    

    Add the extension in AppServiceProvider:

    $this->app->make(\Twig\Environment::class)->addExtension(new \Twig\Extensions\DebugExtension());
    

Integration Tips

  1. Lazy-Loading Extensions Register extensions conditionally based on environment or features:

    if ($this->app->environment('local')) {
        $this->app->make(\Twig\Environment::class)->addExtension(new \Twig\Extensions\DebugExtension());
    }
    
  2. Custom Filters/Functions Extend Twig with custom logic by creating a custom extension:

    use Twig\Extension\AbstractExtension;
    use Twig\TwigFunction;
    
    class CustomExtension extends AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new TwigFunction('custom_function', [$this, 'customFunction']),
            ];
        }
    
        public function customFunction($input)
        {
            return strtoupper($input) . ' (custom)';
        }
    }
    

    Register it in AppServiceProvider:

    $this->app->make(\Twig\Environment::class)->addExtension(new CustomExtension());
    
  3. Caching Extensions Ensure extensions are registered before the Twig environment is cached (e.g., in bootstrap/cache). Rebuild the cache after adding new extensions:

    php artisan config:cache
    php artisan view:cache
    

Gotchas and Tips

Pitfalls

  1. Extension Conflicts

    • Some extensions (e.g., IntlExtension) require the intl PHP extension. Verify dependencies:
      php -m | grep intl
      
    • If using multiple extensions that modify the same Twig environment (e.g., StringExtension and a custom extension with overlapping filters), ensure consistent behavior by testing edge cases.
  2. Markdown Parsing Quirks

    • The default MarkdownExtension uses Parsedown, which may not support all Markdown features (e.g., tables, footnotes). Use ParsedownExtra for extended syntax:
      new MarkdownExtension(new \ParsedownExtra())
      
    • Sanitize Markdown input if rendering user-generated content to prevent XSS:
      {{ markdown_content|markdown|striptags }}
      
  3. Performance Overhead

    • Extensions like DebugExtension or heavy Markdown parsers can slow down template rendering. Disable them in production:
      if (!$this->app->environment('local')) {
          // Skip adding debug/heavy extensions
      }
      
  4. Twig Version Compatibility

    • The twig/extensions package is archived and may not support the latest Twig versions. Check compatibility with your Laravel/Twig versions (e.g., Laravel 9 uses Twig 3.x). Use twig/twig for core and twig/extensions selectively.

Debugging Tips

  1. Enable Twig Debug Mode Add this to your AppServiceProvider to debug template rendering:

    $this->app->make(\Twig\Environment::class)->setDebug($this->app->environment('local'));
    
  2. Inspect Available Filters/Functions Dump all available Twig functions/filters in a template:

    {% set functions = _context.getFunctions() %}
    {% set filters = _context.getFilters() %}
    {{ dump(functions) }}
    {{ dump(filters) }}
    
  3. Extension Registration Order Extensions are additive. If a filter/function isn’t working, ensure:

    • The extension is registered before the template is rendered.
    • No other extension is overriding it (e.g., a custom extension with the same name).

Extension Points

  1. Override Default Extensions Replace built-in extensions (e.g., StringExtension) with a custom subclass:

    class CustomStringExtension extends \Twig\Extensions\StringExtension
    {
        public function getFilters()
        {
            $filters = parent::getFilters();
            $filters['custom_upper'] = [$this, 'customUpper'];
            return $filters;
        }
    
        public function customUpper($string)
        {
            return strtoupper($string) . ' (custom)';
        }
    }
    
  2. Add Global Variables Use extensions to inject global variables into all templates:

    class GlobalVarsExtension extends AbstractExtension
    {
        public function getGlobals()
        {
            return [
                'app_name' => 'MyApp',
                'config' => config()->all(),
            ];
        }
    }
    
  3. Test Extensions Isolated Test extensions in isolation using Laravel’s TwigView or a standalone Twig environment:

    $twig = new \Twig\Environment($loader, ['debug' => true]);
    $twig->addExtension(new \Twig\Extensions\StringExtension());
    echo $twig->render('template.twig', ['input' => 'test']);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware