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

Swift Twig Laravel Package

botnyx/swift-twig

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install Dependencies:

    composer require twig/twig symfony/dom-crawler spatie/laravel-swiftmailer
    
    • twig/twig: For templating.
    • symfony/dom-crawler: Required for inline image handling.
    • spatie/laravel-swiftmailer: To integrate SwiftMailer with Laravel.
  2. Configure SwiftMailer: Publish and configure SwiftMailer settings:

    php artisan vendor:publish --provider="Spatie\SwiftMailer\SwiftMailerServiceProvider"
    

    Update .env with your mail configuration (e.g., SMTP settings).

  3. Set Up Twig: Register Twig in config/app.php under providers:

    Twig\Extension\CoreExtension::class,
    Twig\Extension\DebugExtension::class,
    

    Configure Twig in config/services.php:

    'twig' => [
        'paths' => [
            resource_path('views/emails'),
        ],
    ],
    
  4. Create a Twig Email Template: Save a template at resources/views/emails/welcome.mail.twig:

    {% block subject %}
        Welcome to Our Platform, {{ user.name }}!
    {% endblock %}
    
    {% block body_text %}
        Hello {{ user.name }},
    
        Thank you for signing up!
    {% endblock %}
    
    {% block body_html %}
        <h1>Hello {{ user.name }},</h1>
        <p>Thank you for signing up!</p>
        <img src="/images/logo.png" class="inline-image" alt="Logo">
    {% endblock %}
    
  5. Send the First Email: In a controller or service:

    use WMC\SwiftmailerTwigBundle\TwigSwiftHelper;
    use Swift_Message;
    
    public function sendWelcomeEmail()
    {
        $twig = app('twig');
        $webDir = public_path();
        $helper = new TwigSwiftHelper($twig, $webDir);
    
        $message = (new Swift_Message())
            ->setTo('user@example.com')
            ->setFrom('noreply@example.com');
    
        $data = ['user' => ['name' => 'John Doe']];
        $helper->populateMessage($message, 'emails/welcome.mail.twig', $data);
    
        app('swiftmailer')->send($message);
    }
    

Implementation Patterns

Usage Patterns

1. Template Organization

  • Store email templates in resources/views/emails/ with .mail.twig extension.
  • Use a consistent naming convention (e.g., user_activation.mail.twig, password_reset.mail.twig).
  • Group related templates in subdirectories (e.g., resources/views/emails/notifications/).

2. Dynamic Data Injection

  • Pass data to templates as associative arrays:
    $data = [
        'user' => ['name' => 'Jane Doe', 'email' => 'jane@example.com'],
        'reset_link' => 'https://example.com/reset-password?token=123',
    ];
    
  • Access data in Twig:
    {% block subject %}
        Reset Your Password, {{ user.name }}
    {% endblock %}
    

3. Reusable Template Components

  • Create base templates with blocks for common elements (e.g., headers, footers):
    {# resources/views/emails/_layout.mail.twig #}
    {% block header %}
        <h1>Our Company</h1>
    {% endblock %}
    
    {% block content %}
        {{ include('emails/' ~ template_name ~ '.mail.twig') }}
    {% endblock %}
    
    {% block footer %}
        <p>© 2023 Our Company</p>
    {% endblock %}
    
  • Extend in child templates:
    {% extends 'emails/_layout.mail.twig' %}
    {% block content %}
        <p>Hello {{ user.name }},</p>
    {% endblock %}
    

4. Inline Images

  • Add class="inline-image" to <img> tags with absolute paths (starting with /):
    <img src="/images/logo.png" class="inline-image" alt="Logo">
    
  • Ensure images are accessible from the public directory (e.g., public/images/).

5. Fallback for Plaintext Emails

  • Always include a body_text block for compatibility with email clients that strip HTML:
    {% block body_text %}
        Hello {{ user.name }},
    
        Please click the link below to reset your password:
        {{ reset_link }}
    
        Best regards,
        The Team
    {% endblock %}
    

6. Testing Templates

  • Use Laravel’s Mail facade to preview emails locally:
    use Illuminate\Support\Facades\Mail;
    
    Mail::raw('Test email body', function ($message) {
        $message->to('test@example.com')
                ->subject('Test Subject');
    });
    
  • For Twig templates, create a helper method to render templates without sending:
    public function renderEmailTemplate(string $template, array $data): string
    {
        $twig = app('twig');
        return $twig->render("emails/{$template}", $data);
    }
    

Workflows

Daily Development Workflow

  1. Create/Edit Templates:

    • Edit Twig templates in resources/views/emails/.
    • Use Laravel Mix or Vite to compile assets (e.g., inline CSS/JS) if needed.
  2. Send Test Emails:

    • Use a local SMTP server (e.g., MailHog) to test emails during development:
      docker run -d -p 1025:1025 -p 8025:8025 mailhog/mailhog
      
    • Configure Laravel’s .env:
      MAIL_MAILER=smtp
      MAIL_HOST=localhost
      MAIL_PORT=1025
      
  3. Debugging:

    • Check MailHog at http://localhost:8025 for rendered emails.
    • Use Twig’s debug mode to inspect template errors:
      $twig->enableDebug(); // In development only!
      
  4. Version Control:

    • Commit Twig templates to Git alongside Blade templates.
    • Document template variables and usage in a README.md in the resources/views/emails/ directory.

Deployment Workflow

  1. Template Updates:

    • Deploy Twig templates alongside Laravel code (no separate asset pipeline needed for templates).
  2. Environment-Specific Data:

    • Use Laravel’s config to pass environment-specific data (e.g., branding colors, logos):
      $data = array_merge($data, [
          'brand_color' => config('mail.brand_color'),
          'support_email' => config('mail.support_email'),
      ]);
      
  3. Caching:

    • Disable Twig caching in production if templates are frequently updated:
      $twig->setCache(false);
      

Integration Tips

Laravel Mail Facade Integration

  • Create a custom mailer class to bridge Laravel’s Mail facade with SwiftMailer/Twig:
    use Illuminate\Mail\Mailable;
    use WMC\SwiftmailerTwigBundle\TwigSwiftHelper;
    
    class TwigMailable extends Mailable
    {
        public function build()
        {
            $helper = new TwigSwiftHelper(app('twig'), public_path());
            $message = (new Swift_Message())
                ->setTo($this->recipient)
                ->setFrom(config('mail.from.address'));
    
            $helper->populateMessage($message, $this->template, $this->data);
    
            return $message;
        }
    }
    
  • Use in controllers:
    Mail::to('user@example.com')->send(new TwigMailable('emails/welcome.mail.twig', $data));
    

Queueing Emails

  • Queue email sending for better performance:
    Mail::to('user@example.com')->queue(new TwigMailable('emails/welcome.mail.twig', $data));
    
  • Process queued emails with Laravel’s queue worker:
    php artisan queue:work
    

Localization

  • Use Laravel’s localization features to support multiple languages in emails:
    {% block subject %}
        {{ 'welcome.subject'|trans(['name' => user.name]) }}
    {% endblock %}
    
  • Store translations in resources/lang/{locale}/emails.php:
    return [
        'welcome.subject' => 'Welcome, :name!',
    ];
    

Dynamic Attachments

  • Attach files dynamically in the populateMessage call:
    $message->attach($filePath, [
        'as' => '
    
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