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

Laravel Larakit Twig Laravel Package

larakit/laravel-larakit-twig

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require larakit/laravel-larakit-twig
    

    Publish the config file:

    php artisan vendor:publish --provider="Larakit\Twig\TwigServiceProvider" --tag="config"
    
  2. Basic Configuration Edit config/twig.php to define:

    • paths (where Twig templates are stored)
    • extensions (enabled Twig extensions)
    • cache (Twig cache directory)
  3. First Use Case: Rendering a Twig Template

    use Larakit\Twig\Facades\Twig;
    
    $content = Twig::render('path/to/template.twig', ['data' => 'value']);
    return response($content);
    
  4. Blade Integration (Optional) Add to config/twig.php:

    'blade' => [
        'enabled' => true,
        'prefix' => '@twig',
    ],
    

    Now use Twig templates in Blade:

    @twig('path/to/template.twig', ['data' => 'value'])
    

Implementation Patterns

Workflows

  1. Template Organization

    • Use paths in config to define multiple template directories (e.g., views, emails, partials).
    • Example:
      'paths' => [
          resource_path('views/twig'),
          resource_path('views/emails'),
      ],
      
  2. Dynamic Template Resolution

    • Resolve templates dynamically with fallbacks:
      $template = Twig::resolve('user/{id}.twig', ['id' => 123]);
      
  3. Reusable Components

    • Create Twig components (e.g., components/header.twig) and include them:
      {% include 'components/header.twig' %}
      
  4. Email Templates

    • Store email templates in resources/views/emails and render them:
      $email = Twig::render('emails/welcome.twig', ['user' => $user]);
      

Integration Tips

  1. Larakit Modules

    • Combine with other Larakit modules (e.g., laravel-larakit-mail) for seamless email templating:
      Mail::sendTwig('emails/order-confirmation.twig', ['order' => $order]);
      
  2. Frontend Integration

    • Use Twig for frontend rendering (e.g., SPAs) by returning JSON responses with Twig-rendered HTML:
      return response()->json([
          'html' => Twig::render('partials/dashboard.twig'),
      ]);
      
  3. API Responses

    • Serve Twig-rendered HTML for API endpoints (e.g., PDF generation):
      return Twig::render('pdf/invoice.twig', ['invoice' => $invoice]);
      
  4. Testing

    • Mock Twig in tests:
      $this->app->instance('twig', Mockery::mock('overload:\Larakit\Twig\TwigManager'));
      

Gotchas and Tips

Pitfalls

  1. Caching Issues

    • Clear Twig cache after changes:
      php artisan twig:clear
      
    • Disable caching in config/twig.php during development:
      'cache' => false,
      
  2. Namespace Conflicts

    • Ensure Twig template paths don’t conflict with Blade paths. Use distinct directories.
  3. Extension Loading

    • Custom Twig extensions must be registered in config/twig.php under extensions:
      'extensions' => [
          \Larakit\Twig\Extensions\MyExtension::class,
      ],
      
  4. Blade vs. Twig Confusion

    • Avoid mixing @twig directives in Blade files with Twig syntax directly. Use one or the other per template.

Debugging

  1. Template Not Found

    • Verify paths in config/twig.php and check for typos in template names.
  2. Syntax Errors

    • Enable Twig debug mode in config/twig.php:
      'debug' => env('APP_DEBUG', false),
      
    • Check browser console or Laravel logs for Twig-specific errors.
  3. Variable Scope

    • Twig variables passed to templates are not automatically available in Blade. Pass them explicitly:
      return view('blade-template', ['twig_data' => Twig::render('twig-template.twig')]);
      

Extension Points

  1. Custom Filters

    • Create a Twig extension for reusable filters:
      namespace App\Extensions;
      
      use Twig\TwigFilter;
      
      class StringExtensions extends \Twig\Extension\AbstractExtension
      {
          public function getFilters()
          {
              return [
                  new TwigFilter('slugify', [$this, 'slugify']),
              ];
          }
      
          public function slugify($string)
          {
              return Str::slug($string);
          }
      }
      
    • Register it in config/twig.php:
      'extensions' => [
          \App\Extensions\StringExtensions::class,
      ],
      
  2. Global Variables

    • Add global variables via a service provider:
      public function boot()
      {
          Twig::share('app_name', config('app.name'));
      }
      
  3. Custom Functions

    • Extend Twig with custom functions similarly to filters, using TwigFunction instead of TwigFilter.
  4. Overriding Default Behavior

    • Bind your own TwigManager implementation to override default behavior:
      $this->app->bind('twig', function ($app) {
          return new \App\Services\CustomTwigManager($app);
      });
      
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