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

Mthaml Laravel Package

dnl/mthaml

Laravel package integrating Haml templating via mthaml, enabling you to render .haml views with a concise, Ruby-like syntax. Useful for teams adopting Haml in PHP/Laravel projects and keeping view markup clean and expressive.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require dnl/mthaml
    
    • Ensure your project uses PHP 5.4+ (Laravel 5.4+ compatible).
  2. First HAML File Create a .haml file in resources/views/ (e.g., welcome.haml):

    %html
      %head
        %title Welcome
      %body
        %h1= greeting
        %p= message
    
  3. Render in a Controller

    use Dnl\MtHaml\MtHaml;
    
    public function showWelcome()
    {
        $haml = new MtHaml();
        $output = $haml->renderFile(
            'welcome.haml',
            ['greeting' => 'Hello, Laravel!', 'message' => 'This is HAML in PHP.']
        );
        return response($output);
    }
    
    • Output: Renders as HTML (equivalent to Blade/Twig).
  4. Leverage Laravel’s View System (Optional) Extend Laravel’s view resolver to handle .haml files:

    // app/Providers/AppServiceProvider.php
    use Illuminate\Support\Facades\View;
    use Dnl\MtHaml\MtHaml;
    
    public function boot()
    {
        View::addExtension('haml', function ($view, $compiler) {
            $haml = new MtHaml();
            $content = $haml->render($view->getPath(), $view->getData());
            return $compiler->compileString($content);
        });
    }
    

    Now use HAML like Blade:

    return view('welcome.haml', ['greeting' => 'Hello']);
    

Implementation Patterns

Core Workflows

  1. Template Inheritance

    • HAML Layouts: Define a base layout (layout.haml):
      %html
        %head
          %title= title
        %body
          = yield
      
    • Child Templates: Extend it (home.haml):
      - title = "Home Page"
      %h1 Welcome
      = yield
      
    • Render Logic:
      $haml->renderFile('home.haml', []);
      
  2. Partials/Includes

    • Partial File (_header.haml):
      %header
        %h2= title
      
    - **Include in Parent**:
      ```haml
      = render('_header.haml', { title: "Dashboard" })
    
    • Laravel Integration: Use View::make() for partials:
      $header = view('partials.header', ['title' => 'Dashboard'])->render();
      
  3. Dynamic Content

    • Loops:
      %ul
        - foreach $items as $item
          %li= $item
      
    • Conditionals:
      - if $show_button
        %button Click Me
      
  4. Multi-Target Output

    • Generate Twig:
      $haml->setTarget('twig')->renderFile('template.haml');
      
    • Use Output in Laravel:
      $twigContent = $haml->renderFile('template.haml', [], 'twig');
      // Pass to Twig template engine or save to file.
      

Laravel-Specific Patterns

  1. Blade-Like Directives Create a custom HAML directive to mimic Blade:

    - @if($condition)
      %p This is a conditional block.
    
    • Implementation:
      $haml->addDirective('@if', function ($args) {
          return "<?php if({$args}): ?>";
      });
      
  2. Service Container Integration Bind MtHaml to Laravel’s container:

    $app->bind(MtHaml::class, function ($app) {
        return new MtHaml(['cache_path' => storage_path('haml_cache')]);
    });
    
    • Usage in Controllers:
      use Illuminate\Support\Facades\App;
      
      $haml = App::make(MtHaml::class);
      
  3. Caching Compiled Templates Enable caching for performance:

    $haml = new MtHaml(['cache' => true, 'cache_path' => storage_path('haml_cache')]);
    
    • Cache Invalidation: Clear cache after HAML file changes:
      php artisan haml:clear  # (Requires custom Artisan command)
      
  4. Asset Pipeline Integration Use HAML for views in Laravel Mix/Vite:

    %link{rel: "stylesheet", href: mix('css/app.css')}
    
    • Compilation: Ensure mix() or @vite() directives are handled by a custom HAML filter.

Gotchas and Tips

Pitfalls

  1. Indentation Sensitivity

    • Issue: HAML is whitespace-sensitive. A misaligned tab/spaces breaks rendering.
      %div  # Wrong: Extra space causes syntax error
        %p Content
      
    • Fix: Use a HAML linter (e.g., haml-lint) or configure your IDE (PHPStorm/VSCode) to highlight indentation issues.
  2. Twig/Blade Syntax Conflicts

    • Issue: HAML’s = for output conflicts with Twig’s {{ }} or Blade’s {!! !!}.
      %p= $variable  # Outputs raw value (no escaping)
      
    • Fix: Use {{ }} for safe output in Twig mode:
      %p {{ $variable }}  # Escaped output (Twig target)
      
  3. Dynamic Content Quirks

    • Issue: PHP variables in HAML ($var) may not auto-escape like Blade’s {!! !!}.
      %p= $user->name  # Unescaped HTML possible
      
    • Fix: Explicitly escape or configure the compiler:
      $haml->setEscapeFunction('htmlspecialchars');
      
  4. Partial Path Resolution

    • Issue: render() fails if partials aren’t in the expected path.
      = render('partials/_header')  # Fails if path is wrong
      
    • Fix: Use absolute paths or configure a base directory:
      $haml->setPartialPath('resources/views/partials');
      
  5. Caching Gotchas

    • Issue: Cached HAML templates may not update until cache is cleared.
      php artisan view:clear  # Clears Laravel's view cache (may not affect HAML)
      
    • Fix: Implement a custom Artisan command to clear HAML cache:
      // app/Console/Commands/ClearHamlCache.php
      public function handle()
      {
          $haml = new MtHaml(['cache_path' => storage_path('haml_cache')]);
          $haml->clearCache();
      }
      

Debugging Tips

  1. Enable Verbose Output

    $haml = new MtHaml(['debug' => true]);
    
    • Logs parsing errors and template paths.
  2. Check Compiled Output Temporarily save compiled templates to debug:

    $haml->setTarget('php')->renderFile('template.haml', [], true); // Save to file
    
  3. IDE Support

  4. Common Errors & Fixes

    Error Cause Solution
    ParseError: syntax error Invalid HAML syntax Validate with haml-lint or IDE.
    Undefined variable $var Variable not passed to template Ensure data is passed to renderFile().
    File not found Incorrect partial path Use absolute paths or configure base dir.
    Twig Error: [Syntax] ... HAML-to-Twig conversion issue Check Twig syntax rules in HAML docs.
    FatalError: Class not found Missing PHP class
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