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

  1. Installation Add the bundle via Composer (included by default in Symfony Flex):

    composer require symfony/twig-bundle
    

    No additional configuration is needed for basic usage—it auto-registers with Symfony’s kernel.

  2. First Use Case: Rendering a Template Create a template at templates/base.html.twig:

    <!DOCTYPE html>
    <html>
    <head>
        <title>{% block title %}Welcome!{% endblock %}</title>
    </head>
    <body>
        {% block body %}{% endblock %}
    </body>
    </html>
    

    Render it in a controller:

    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    
    class HomeController extends AbstractController
    {
        public function index(): Response
        {
            return $this->render('base.html.twig', [
                'title' => 'Custom Title',
            ]);
        }
    }
    
  3. Where to Look First

    • Symfony Docs: Twig Integration
    • Bundle Config: config/packages/twig.yaml (auto-generated).
    • Debugging: Use {{ dump() }} in templates or var_dump() in PHP for debugging.

Implementation Patterns

Core Workflows

  1. Template Inheritance Extend base templates with {% extends 'base.html.twig' %} and override blocks ({% block body %}). Example: Create templates/home.html.twig:

    {% extends 'base.html.twig' %}
    {% block body %}
        <h1>Hello, {{ name }}!</h1>
    {% endblock %}
    
  2. Passing Data to Templates Use the render() method in controllers or pass data via ->with():

    $this->render('home.html.twig', ['name' => 'John']);
    
  3. Embedding Components Reuse template fragments with {% include %} or {% embed %}:

    {% include 'partials/_navbar.html.twig' %}
    {% embed 'layouts/app.html.twig' %}
        {% block content %}{% endblock %}
    {% endembed %}
    
  4. Global Variables Define globals in twig.yaml:

    twig:
        globals:
            app_name: 'MyApp'
    

    Access them in templates: {{ app_name }}.

  5. Asset Management Use {{ asset() }} for static files (configured in framework.yaml):

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

Integration Tips

  • Symfony Forms: Auto-render forms with {{ form(row) }} (requires Symfony\Bridge\Twig\Extension\FormExtension).
  • Translation: Use {{ 'home.title'|trans }} (configured in framework.yaml).
  • Debug Toolbar: Enable Twig profiler in config/packages/dev/twig.yaml:
    twig:
        debug: true
    
  • Custom Filters/Functions: Create a Twig extension:
    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions(): array
        {
            return [
                new \Twig\TwigFunction('greet', [$this, 'greetUser']),
            ];
        }
        public function greetUser(string $name): string
        {
            return "Hello, $name!";
        }
    }
    
    Register it as a service (auto-discovered via autoconfigure: true).

Gotchas and Tips

Pitfalls

  1. Caching Headaches

    • Twig templates are cached by default in production. Clear cache after changes:
      php bin/console cache:clear
      
    • Debug mode (twig.debug: true) disables caching but slows performance.
  2. Autoloading Issues

    • Ensure template paths are correct. Use bin/console debug:autowiring to verify services.
    • Common paths: templates/, templates/{controller_name}/.
  3. Variable Scope

    • Variables passed to render() are only available in that template unless extended.
    • Use {% set %} for local variables or globals for app-wide access.
  4. Deprecated Syntax

    • Avoid {{ include }} (use {% include %}).
    • Prefer {{ form_widget() }} over {{ form() }} for clarity.
  5. Security

    • Escape variables automatically: {{ user.input }} (safe) vs. {{ user.input|raw }} (unsafe).
    • Use {{ form_row(form.field) }} to auto-escape form fields.

Debugging

  • Template Errors: Check var/log/dev.log or enable Twig’s debug mode.
  • Undefined Variables: Use {{ dump(var) }} or {{ var|default('fallback') }}.
  • Performance: Profile with Symfony Profiler (_profiler route) or twig:debug command:
    php bin/console twig:debug
    

Extension Points

  1. Custom Paths Add custom template paths in twig.yaml:

    twig:
        paths:
            '%kernel.project_dir%/templates/custom': ~
    
  2. Environment-Specific Config Override settings per environment (e.g., config/packages/dev/twig.yaml):

    twig:
        strict_variables: true  # Fail on undefined vars
    
  3. Event Listeners Listen to Twig events (e.g., Twig\Event\SourceContextLoadedEvent) for runtime modifications:

    // src/EventListener/TwigListener.php
    class TwigListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                TwigEvent::SOURCE_CONTEXT_LOADED => 'onSourceContextLoaded',
            ];
        }
        public function onSourceContextLoaded(TwigEvent $event): void
        {
            $context = $event->getSourceContext();
            // Modify template logic here
        }
    }
    
  4. Runtime Template Overrides Use Twig\Environment::createTemplate() to dynamically generate templates:

    $template = $this->get('twig')->createTemplate('Hello {{ name }}!');
    echo $template->render(['name' => 'Alice']);
    

Pro Tips

  • Partial Caching: Use {% cache %} for static fragments:
    {% cache 'sidebar' %}
        {% include 'partials/sidebar.html.twig' %}
    {% endcache %}
    
  • Macros: Define reusable components in _macros.html.twig:
    {% macro alert(type, message) %}
        <div class="alert alert-{{ type }}">{{ message }}</div>
    {% endmacro %}
    
    Include and use:
    {% import '_macros.html.twig' as macros %}
    {{ macros.alert('success', 'Saved!') }}
    
  • Symfony UX: Integrate with Symfony UX for live components (e.g., Stimulus):
    {{ stimulus_controller('hello_controller', {'name': 'World'}) }}
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle