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

Email Template Bundle Laravel Package

avtonom/email-template-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require avtonom/email-template-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Avtonom\EmailTemplateBundle\AvtonomEmailTemplateBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run the bundle’s migration to create the required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

    The bundle creates:

    • email_template (stores template content, name, and metadata)
    • email_template_layout (optional layouts for consistent styling)
  3. First Template Create a template via the admin interface (if configured) or manually via Doctrine:

    $template = new \Avtonom\EmailTemplateBundle\Entity\EmailTemplate();
    $template->setName('welcome_email');
    $template->setContent('{% extends "base_email.html.twig" %}{% block content %}Hello {{ user.name }}{% endblock %}');
    $template->setIsActive(true);
    $em->persist($template);
    $em->flush();
    
  4. First Usage Render and send an email in a controller:

    use Avtonom\EmailTemplateBundle\Service\EmailTemplateRenderer;
    
    public function sendWelcomeEmail(EmailTemplateRenderer $renderer, $user)
    {
        $template = $renderer->render('welcome_email', ['user' => $user]);
        // Use SwiftMailer to send $template (see Implementation Patterns).
    }
    

Implementation Patterns

Core Workflow

  1. Template Management

    • Database-Driven: Store templates in email_template table with Twig syntax.
    • Layouts: Extend base layouts (e.g., base_email.html.twig) for consistent headers/footers.
    • I18N Support: Use Twig’s trans filter or pass translated variables (e.g., ['greeting' => $this->translator->trans('welcome')]).
  2. Rendering Templates Inject EmailTemplateRenderer service to fetch and render templates:

    $html = $renderer->render('template_name', ['var1' => 'value1']);
    
    • Caching: Enable Twig’s cache (twig.cache_warmer) for performance.
    • Fallbacks: Handle missing templates with a TemplateNotFoundException listener.
  3. Integration with SwiftMailer Combine with Symfony’s Mailer component:

    $email = (new Email())
        ->to($user->getEmail())
        ->subject('Welcome!')
        ->html($renderer->render('welcome_email', ['user' => $user]));
    $mailer->send($email);
    
  4. Admin Interface (Optional) If using the bundle’s admin, configure fos_user or sonata_admin bundles to manage templates via UI.

Advanced Patterns

  • Dynamic Templates: Use template variables to customize emails per user/role:
    {# templates/welcome_email.html.twig #}
    {% if user.is_premium %}
        <p>Enjoy premium features!</p>
    {% endif %}
    
  • Template Versioning: Add a version field to email_template for A/B testing or rollbacks.
  • Asset Management: Store static assets (images/CSS) in public/ and reference them in templates:
    <img src="{{ asset('images/logo.png') }}" alt="Logo">
    

Gotchas and Tips

Pitfalls

  1. Twig Version Mismatch

    • The bundle requires Twig 1.3+. Conflicts may arise if other bundles enforce older versions.
    • Fix: Pin Twig in composer.json:
      "twig/twig": "^1.3|^2.0"
      
  2. Database Schema Changes

    • The bundle’s migrations assume default Doctrine configurations. Custom entity managers may break migrations.
    • Fix: Manually adjust src/Resources/config/doctrine/ if needed.
  3. Template Not Found

    • Throws TemplateNotFoundException if the template name doesn’t match the database.
    • Debug: Verify the template is active (is_active = 1) and the name matches exactly (case-sensitive).
  4. SwiftMailer HTML Sanitization

    • SwiftMailer may strip HTML tags if not configured properly.
    • Fix: Ensure SwiftMailer is set to preserve HTML:
      # config/packages/swiftmailer.yaml
      swiftmailer:
          spool: { type: memory }
          default_mailer: default
          mailers:
              default:
                  transport: %env(MAILER_DSN)%
                  defaults:
                      html: true  # Critical for HTML emails
      

Debugging Tips

  • Twig Errors: Enable Twig’s debug mode in config/packages/twig.yaml:
    twig:
        debug: '%kernel.debug%'
        strict_variables: '%kernel.debug%'
    
  • Template Content: Log rendered output to verify variables:
    file_put_contents(
        'debug/email_template.html',
        $renderer->render('template_name', $data)
    );
    
  • Database Dumps: Use Doctrine’s query logging to check template retrieval:
    $em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    

Extension Points

  1. Custom Template Storage Override the EmailTemplateRepository to fetch templates from an API or S3:

    // src/Service/CustomEmailTemplateRepository.php
    class CustomEmailTemplateRepository extends \Avtonom\EmailTemplateBundle\Repository\EmailTemplateRepository
    {
        public function findOneByName($name)
        {
            // Custom logic (e.g., API call)
        }
    }
    

    Register as a service:

    services:
        Avtonom\EmailTemplateBundle\Repository\EmailTemplateRepository:
            alias: custom.email_template.repository
    
  2. Pre-Render Hooks Extend the EmailTemplateRenderer to add logic before rendering:

    $renderer->addPreRenderListener(function ($template, $data) {
        $data['current_year'] = date('Y');
        return $data;
    });
    
  3. Layout Overrides Replace default layouts by overriding the Twig loader:

    twig:
        paths:
            '%kernel.project_dir%/templates/email': email
    

    Ensure your base_email.html.twig extends from email/base_email.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.
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