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

Templating Laravel Package

symfony/templating

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require symfony/templating
    

    No additional configuration is needed for basic usage—just autoload the Symfony\Component\Templating\TemplateNameParser and Symfony\Component\Templating\EngineInterface classes.

  2. First Use Case: Rendering a Template

    use Symfony\Component\Templating\EngineInterface;
    use Symfony\Component\Templating\TemplateNameParser;
    
    // Initialize the parser (handles template name resolution)
    $parser = new TemplateNameParser();
    
    // Use a templating engine (e.g., PHP, Twig, or a custom one)
    $engine = new \Symfony\Component\Templating\PhpEngine(
        new \Symfony\Component\Templating\Loader\FilesystemLoader('/path/to/templates')
    );
    
    // Render a template
    $content = $engine->render('template.html.twig', ['name' => 'John']);
    
  3. Where to Look First

    • Documentation: Symfony Templating Component (official docs).
    • Core Classes:
      • EngineInterface: The main interface for templating engines.
      • TemplateNameParser: Resolves template names (e.g., @Bundle/Controller/template.html.twig).
      • LoaderInterface: Loads template content (e.g., FilesystemLoader, FilesystemLoader for files, ChainLoader for multiple sources).
    • Built-in Engines:
      • PhpEngine: Renders PHP templates (e.g., .html.php).
      • TwigEngine: Integrates with Twig (requires twig/twig).
      • PhpEngine is the simplest for quick prototyping.

Implementation Patterns

1. Template Loading Strategies

  • FilesystemLoader: For static templates in a directory.
    $loader = new \Symfony\Component\Templating\Loader\FilesystemLoader('/templates');
    $engine = new \Symfony\Component\Templating\PhpEngine($loader);
    
  • ChainLoader: Combine multiple loaders (e.g., filesystem + cache).
    $loaders = [
        new \Symfony\Component\Templating\Loader\FilesystemLoader('/app/templates'),
        new \Symfony\Component\Templating\Loader\FilesystemLoader('/vendor/templates'),
    ];
    $loader = new \Symfony\Component\Templating\Loader\ChainLoader($loaders);
    
  • Custom Loader: Implement LoaderInterface for dynamic templates (e.g., database-backed templates).

2. Template Inheritance and Blocks

Use PHP templating with yield and extends (similar to Twig):

// base.html.php
<html>
    <body>
        <?php yield('content') ?>
    </body>
</html>

// child.html.php
<?php $view->extend('base.html.php') ?>
<?php $view->block('content') ?>
    <h1>Hello, <?php echo $name ?></h1>
<?php endblock() ?>

Render with:

$engine->render('child.html.php', ['name' => 'John']);

3. Integration with Laravel

  • Service Provider: Bind the templating engine to Laravel’s container:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('templating', function () {
            $loader = new \Symfony\Component\Templating\Loader\FilesystemLoader(resource_path('views'));
            return new \Symfony\Component\Templating\PhpEngine($loader);
        });
    }
    
  • Helper Method: Add a facade or helper for easy rendering:
    // app/Helpers/Templating.php
    function renderTemplate(string $template, array $data = []): string
    {
        return app('templating')->render($template, $data);
    }
    
  • Blade Compatibility: Use PhpEngine to render Blade templates (if pre-compiled to PHP).

4. Dynamic Template Resolution

  • Template Name Parsing: Resolve templates with bundles or namespaces:
    $parser = new TemplateNameParser();
    $templateName = $parser->parse('@AcmeBundle/Template/template.html.twig');
    // Resolves to '/path/to/AcmeBundle/Resources/views/Template/template.html.twig'
    
  • Fallback Logic: Handle missing templates gracefully:
    try {
        $engine->render($templateName, $data);
    } catch (\Symfony\Component\Templating\TemplateNotFoundException $e) {
        // Fallback to a default template
        $engine->render('default.html.php', $data);
    }
    

5. Caching Templates

  • Cache Loader: Wrap a loader with a cache layer:
    $cacheLoader = new \Symfony\Component\Templating\Loader\FilesystemLoader(
        '/templates',
        new \Symfony\Component\Cache\Simple\FilesystemCache('/cache')
    );
    
  • Manual Caching: Cache rendered output (e.g., in Laravel’s cache):
    $cacheKey = 'template_' . md5($template . serialize($data));
    $content = Cache::remember($cacheKey, 3600, function () use ($engine, $template, $data) {
        return $engine->render($template, $data);
    });
    

Gotchas and Tips

Pitfalls

  1. Template Path Resolution

    • Issue: FilesystemLoader throws TemplateNotFoundException if the path is incorrect.
    • Fix: Use absolute paths or ensure the loader’s root directory is correct.
      $loader = new \Symfony\Component\Templating\Loader\FilesystemLoader(
          app_path('Resources/views') // Laravel-specific
      );
      
  2. Namespace Collisions

    • Issue: @Bundle/Template/template.html.twig may not resolve if the bundle structure isn’t standard.
    • Fix: Customize TemplateNameParser or use absolute paths.
  3. PHP Engine Limitations

    • Issue: PhpEngine doesn’t support Twig’s advanced features (e.g., filters, tests).
    • Fix: Use TwigEngine for Twig-specific functionality or pre-process templates.
  4. Memory Leaks with Caching

    • Issue: Caching rendered templates can bloat memory if not managed.
    • Fix: Use a cache adapter with TTL (e.g., Psr6CacheAdapter) and clear stale entries.
  5. Security Risks

    • Issue: Arbitrary template inclusion can lead to path traversal attacks.
    • Fix: Validate template names and use allowlists:
      $allowedTemplates = ['home.html.php', 'about.html.php'];
      if (!in_array($template, $allowedTemplates)) {
          throw new \InvalidArgumentException('Template not allowed.');
      }
      

Debugging Tips

  1. Enable Debug Mode Symfony’s templating component integrates with the DebugClassLoader for stack traces:

    $loader = new \Symfony\Component\Templating\Loader\FilesystemLoader(
        '/templates',
        null,
        true // Enable debug mode
    );
    
  2. Log Template Not Found Errors Catch TemplateNotFoundException and log the missing template:

    try {
        $engine->render($template, $data);
    } catch (\Symfony\Component\Templating\TemplateNotFoundException $e) {
        \Log::error("Template not found: {$e->getTemplateName()}");
        throw $e;
    }
    
  3. Inspect Rendered Output Use ob_start() to capture output for debugging:

    ob_start();
    $engine->render($template, $data);
    $output = ob_get_clean();
    \Log::debug("Rendered template output: {$output}");
    

Extension Points

  1. Custom Templating Engine Implement EngineInterface for a new engine (e.g., Mustache, Smarty):

    class MyEngine implements EngineInterface
    {
        public function render(string $name, array $parameters): string
        {
            // Custom logic here
            return "Rendered {$name} with " . count($parameters) . " parameters";
        }
    }
    
  2. Template Pre-Processing Extend LoaderInterface to modify templates before rendering:

    class PreprocessingLoader implements LoaderInterface
    {
        private $decorated;
    
        public function __construct(LoaderInterface $decorated)
        {
            $this->decorated = $decorated;
        }
    
        public function load(string $name): string
        {
            $content = $this->decorated->load($name);
            return $this->preprocess($content);
        }
    
        private function preprocess(string $content):
    
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