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

Yii2 Twig Laravel Package

yiisoft/yii2-twig

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yiisoft/yii2-twig
    

    Ensure PHP ≥7.4 (PHP 8 recommended).

  2. Basic Configuration Add to config/web.php:

    'view' => [
        'renderers' => [
            'twig' => [
                'class' => 'yiisoft\yii2\twig\ViewRenderer',
                'cachePath' => '@runtime/Twig/cache',
                'viewPath' => '@app/views',
                'options' => [
                    'auto_reload' => true, // For development
                    'cache' => false,       // Disable caching in dev
                ],
            ],
        ],
    ],
    
  3. First Use Case Rename a view file from index.php to index.twig in your views directory. Render it in a controller:

    return $this->render('index', ['data' => $model]);
    

    Ensure the renderer is set in the view file:

    {% extends 'layout.twig' %}
    {% block content %}
        {{ dump(data) }}
    {% endblock %}
    

Implementation Patterns

Core Workflows

  1. View Rendering

    • Use Twig syntax ({{ }}, {% %}) in .twig files.
    • Pass data via controller:
      return $this->render('twig-view', ['key' => 'value']);
      
    • Access data in Twig:
      {{ key }}  {# Outputs: value #}
      
  2. Layouts and Extends

    • Create a base layout (layout.twig):
      <!DOCTYPE html>
      {% block content %}{% endblock %}
      
    • Extend in child views:
      {% extends 'layout.twig' %}
      {% block content %}
          <h1>Hello, Twig!</h1>
      {% endblock %}
      
  3. Partial Views (Includes)

    • Include reusable components:
      {% include 'partials/header.twig' %}
      
    • Pass variables:
      {% include 'partials/user.twig' with {'name': 'John'} %}
      
  4. Filters and Functions

    • Use Twig’s built-in filters:
      {{ 'hello'|upper }}
      
    • Register custom functions in config/web.php:
      'view' => [
          'renderers' => [
              'twig' => [
                  'class' => 'yiisoft\yii2\twig\ViewRenderer',
                  'options' => [
                      'functions' => [
                          'my_func' => new \Twig\TwigFunction('my_func', function() { return 'custom!'; }),
                      ],
                  ],
              ],
          ],
      ],
      
    • Call in Twig:
      {{ my_func() }}
      
  5. Integration with Yii Helpers

    • Use Yii’s Url, Html, etc., in Twig via yiisoft/yii2-twig-extensions:
      {{ url('site/index') }}
      {{ activeForm(['action' => url('site/contact')]) }}
      

Advanced Patterns

  1. Dynamic View Paths Override getViewPath() in a custom ViewRenderer to load views from multiple locations:

    class CustomViewRenderer extends ViewRenderer {
        public function getViewPath($view) {
            return [Yii::getAlias('@app/views'), Yii::getAlias('@vendor/views')];
        }
    }
    
  2. Caching Strategies

    • Development: Disable caching ('cache' => false).
    • Production: Enable caching and set cachePath:
      'options' => [
          'cache' => true,
          'cache_path' => '@runtime/Twig/cache',
      ],
      
    • Clear cache manually:
      rm -rf runtime/Twig/cache/*
      
  3. Twig Extensions Create a custom Twig extension for reusable logic:

    use Twig\Extension\AbstractExtension;
    use Twig\TwigFunction;
    
    class MyTwigExtension extends AbstractExtension {
        public function getFunctions() {
            return [
                new TwigFunction('greet', [$this, 'greetUser']),
            ];
        }
        public function greetUser($name) {
            return "Hello, $name!";
        }
    }
    

    Register in ViewRenderer:

    'options' => [
        'extensions' => [new MyTwigExtension()],
    ],
    
  4. Error Handling Configure Twig to show errors in development:

    'options' => [
        'debug' => Yii::$app->environment === 'dev',
    ],
    

    Customize error templates by setting error_handler in Twig options.


Gotchas and Tips

Common Pitfalls

  1. File Extensions

    • Issue: Forgetting to rename .php to .twig causes Yii to fall back to PHP rendering.
    • Fix: Ensure all Twig views end with .twig.
  2. Caching in Development

    • Issue: Accidental caching in dev hides template changes.
    • Fix: Always set 'cache' => false and 'auto_reload' => true in dev.
  3. Namespace Conflicts

    • Issue: Twig templates in namespaced directories (e.g., @app/modules/admin/views) may not resolve correctly.
    • Fix: Use absolute paths or override getViewPath() to include module paths.
  4. Yii Widgets in Twig

    • Issue: Yii widgets (e.g., ActiveForm) require yiisoft/yii2-twig-extensions for compatibility.
    • Fix: Install the extension:
      composer require yiisoft/yii2-twig-extensions
      
  5. Autoloading Twig Extensions

    • Issue: Custom Twig extensions not recognized.
    • Fix: Ensure the extension class is autoloaded (Composer autoload:dump).

Debugging Tips

  1. Enable Twig Debug Mode Add to config/web.php:

    'options' => [
        'debug' => true, // Shows Twig errors in dev
    ],
    
  2. Check Template Paths Verify viewPath in config matches your actual view directory:

    'viewPath' => [Yii::getAlias('@app/views'), '@vendor/views'],
    
  3. Clear Runtime Cache If changes aren’t reflected, clear:

    rm -rf runtime/Twig/cache/*
    
  4. Twig Dump and Debug Use Twig’s dump() for debugging:

    {{ dump(variables) }}
    

    Or enable strict_variables in options to catch undefined vars.


Extension Points

  1. Custom View Renderer Extend yiisoft\yii2\twig\ViewRenderer to modify behavior:

    class CustomViewRenderer extends ViewRenderer {
        public function render($view, $params = []) {
            // Pre-process $params or $view
            return parent::render($view, $params);
        }
    }
    
  2. Twig Environment Configuration Override createTwigEnvironment() to customize the Twig environment:

    public function createTwigEnvironment() {
        $loader = new \Twig\Loader\FilesystemLoader($this->getViewPath());
        $options = $this->options;
        $options['cache'] = Yii::$app->environment === 'prod' ? $options['cache_path'] : false;
        return new \Twig\Environment($loader, $options);
    }
    
  3. Integrate with Yii Events Listen to ViewRenderer::EVENT_BEFORE_RENDER to modify data before rendering:

    Yii::$container->set(ViewRenderer::class, [
        'class' => ViewRenderer::class,
        'on beforeRender' => function($event) {
            $event->sender->options['extensions'][] = new MyTwigExtension();
        },
    ]);
    
  4. Asset Management Use Twig’s asset() function with Yii’s AssetBundle:

    <link rel="stylesheet" href="{{ asset('@web/css/style.css') }}">
    

    Ensure @web is configured in UrlManager.

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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium