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

symfony/twig-bundle

Symfony TwigBundle integrates the Twig templating engine into the Symfony full-stack framework, providing seamless configuration, services, and rendering support for templates and views within Symfony applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Developers (Symfony Context)

While symfony/twig-bundle is Symfony-native, Laravel developers evaluating Twig can mirror its patterns. Start here:

  1. Installation (Symfony Equivalent)

    composer require symfony/twig-bundle
    

    For Laravel: Use php-twig + tightenco/jigsaw instead.

  2. First Use Case: Render a Template Configure config/packages/twig.yaml (Symfony):

    twig:
        paths: ['%kernel.project_dir%/templates']
        debug: '%kernel.debug%'
    

    Laravel Equivalent:

    // routes/web.php
    Route::get('/hello', function () {
        return response()->view('hello', ['name' => 'Laravel']);
    });
    
  3. Create a Template templates/hello.html.twig:

    <h1>Hello, {{ name }}!</h1>
    

    Key Twig Features to Try Immediately:

    • Filters: {{ variable|upper }}
    • Loops: {% for item in items %}
    • Includes: {% include 'partials/header.html.twig' %}
  4. Access Twig Environment (Symfony)

    use Symfony\Bundle\TwigBundle\TwigBundle;
    use Twig\Environment;
    
    $twig = $container->get('twig');
    $twig->render('hello.html.twig', ['name' => 'Symfony']);
    

    Laravel Equivalent:

    use Twig\Environment;
    use Twig\Loader\FilesystemLoader;
    
    $loader = new FilesystemLoader('/path/to/templates');
    $twig = new Environment($loader);
    echo $twig->render('hello.html.twig', ['name' => 'Laravel']);
    

Implementation Patterns

1. Template Organization

  • Symfony Convention: Templates live in templates/ (auto-discovered).
    templates/
    ├── base.html.twig          # Base layout
    ├── partials/
    │   ├── header.html.twig
    │   └── footer.html.twig
    └── pages/
        └── home.html.twig
    
  • Laravel Adaptation:
    • Use resources/views/ (Blade default).
    • Extend Twig with jigsaw for asset pipelines.

2. Dynamic Content with Symfony Components

Leverage Symfony’s ecosystem in Twig:

{# Render a Symfony Form #}
{{ form_start(form) }}
    {{ form_row(form.name) }}
    {{ form_row(form.email) }}
    {{ form_end(form) }}

Laravel Equivalent: Use collective/html or Laravel’s native form helpers.

3. Custom Twig Extensions

Create reusable logic:

// src/Twig/AppExtension.php (Symfony)
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

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

    public function greet(string $name): string
    {
        return "Hello, $name!";
    }
}

Usage in Twig:

{{ app_greet('Laravel') }}

Laravel Tip: Register extensions in AppServiceProvider:

$twig->addExtension(new AppExtension());

4. Integration with Symfony Forms

{# templates/contact.html.twig #}
{{ form_theme(form, 'forms/theme.html.twig') }}
{{ form_widget(form) }}

Laravel Tip: Use laravelcollective/html for similar form rendering.

5. Asset Management

Symfony’s asset() function handles versioning:

<img src="{{ asset('images/logo.png') }}" alt="Logo">

Laravel Equivalent: Use asset() helper or mix() for Vite.

6. Debugging and Profiler

Symfony’s Web Profiler shows Twig template timings and errors:

{% if app.debug %}
    {{ dump(app.request) }}
{% endif %}

Laravel Tip: Use dd() or dump() from laravel-debugbar.


Gotchas and Tips

Symfony-Specific Pitfalls

  1. Template Caching

    • Twig templates are cached in %kernel.cache_dir%/twig.
    • Clear cache after changes:
      php bin/console cache:clear
      
    • Laravel Tip: Use php artisan view:clear.
  2. Namespace Conflicts

    • Avoid naming templates after PHP classes (e.g., User.html.twig).
    • Use underscores: user_profile.html.twig.
  3. Debug Mode

    • Set debug: true in twig.yaml for full error details.
    • Warning: Never enable in production.
  4. Template Inheritance

    • Extend base templates:
      {% extends 'base.html.twig' %}
      {% block title %}Homepage{% endblock %}
      
    • Gotcha: Forgetting {% block %} will override content entirely.
  5. Auto-Reloading

    • Symfony’s dev server auto-reloads templates. For production:
      twig:
          auto_reload: false
      

Laravel Adaptation Tips

  1. Avoid Symfony Dependencies

    • Don’t use symfony/twig-bundle in Laravel. Use:
      composer require twig/twig tightenco/jigsaw
      
  2. Blade vs. Twig

    • Twig’s {{ }} vs. Blade’s {!! !!} for escaping.
    • Twig’s {% %} vs. Blade’s @.
  3. Service Container

    • Bind Twig environment in Laravel’s AppServiceProvider:
      $this->app->singleton(TwigEnvironment::class, function ($app) {
          $loader = new FilesystemLoader($app['path.to.views']);
          return new Environment($loader, [
              'cache' => $app['path.to.cache'],
          ]);
      });
      
  4. Custom Directives

    • Twig lacks Blade’s @directives. Use extensions or PHP callbacks.
  5. Performance

    • Precompile Twig templates in Laravel for production:
      php artisan twig:compile
      

Debugging Tricks

  1. Template Not Found?

    • Verify paths in twig.yaml (Symfony) or FilesystemLoader (Laravel).
    • Check for typos in template names (case-sensitive).
  2. Variable Errors

    • Use {{ dump(variable) }} to inspect data.
    • Symfony: {{ app.request.attributes.get('_controller') }} to debug routes.
  3. Extension Not Working?

    • Ensure the extension is tagged as a Twig extension in Symfony’s DI:
      services:
          App\Twig\AppExtension:
              tags: ['twig.extension']
      
  4. Circular References

    • Twig throws Twig\Error\RuntimeError for circular includes.
    • Fix: Use {% include %} with absolute paths or refactor templates.

Extension Points

  1. Custom Filters

    // src/Twig/AppExtension.php
    public function getFilters(): array
    {
        return [
            new TwigFilter('custom_filter', [$this, 'customFilter']),
        ];
    }
    

    Usage:

    {{ 'hello'|custom_filter }}
    
  2. Global Variables

    # config/packages/twig.yaml
    twig:
        globals:
            app_name: 'MyApp'
    

    Access in Twig:

    {{ app_name }}
    
  3. Override Default Settings

    twig:
        strict_variables: true  # Throw errors for undefined vars
        autoescape: utf-8        # Force UTF-8 escaping
    
  4. Integrate with Symfony’s Event System

    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    $dispatcher->addListener(KernelEvents::VIEW, function (GetResponseEvent $event) {
        $twig = $event->getContainer()->get('twig');
        $event->setResponse(new Response($twig->render('custom_response.html.twig')));
    });
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle