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

Commonmark Ext Table Laravel Package

league/commonmark-ext-table

Deprecated CommonMark table extension for PHP. Adds GitHub Flavored Markdown-style tables (alignment, header/body) to league/commonmark environments. Use league/commonmark 1.3+ instead, which includes the same Table extension under League\CommonMark\Extension\Table.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Check Laravel’s commonmark Version: Verify your project uses league/commonmark <1.3 (this package is deprecated in favor of the bundled extension).

    composer show league/commonmark
    

    If ≥1.3, skip to Implementation Patterns and use the built-in TableExtension.

  2. Install the Extension (if using <1.3):

    composer require league/commonmark-ext-table
    
  3. Basic Integration: Add the extension to your Environment in a service provider (e.g., AppServiceProvider):

    use League\CommonMark\Environment;
    use League\CommonMark\Ext\Table\TableExtension;
    
    public function boot()
    {
        $environment = Environment::createCommonMarkEnvironment();
        $environment->addExtension(new TableExtension());
    
        // Store for later use (e.g., in a Markdown service)
        app()->singleton('commonmark.environment', fn() => $environment);
    }
    
  4. First Use Case: Parse a Markdown string with tables into HTML:

    use League\CommonMark\Converter;
    use League\CommonMark\DocParser;
    use League\CommonMark\HtmlRenderer;
    
    $environment = app('commonmark.environment');
    $converter = new Converter(new DocParser($environment), new HtmlRenderer($environment));
    
    $markdown = <<<MD
    | Name     | Role          |
    |----------|---------------|
    | Alice    | Developer     |
    | Bob      | Designer      |
    MD;
    
    echo $converter->convert($markdown);
    

    Output:

    <table>
      <thead>
        <tr><th>Name</th><th>Role</th></tr>
      </thead>
      <tbody>
        <tr><td>Alice</td><td>Developer</td></tr>
        <tr><td>Bob</td><td>Designer</td></tr>
      </tbody>
    </table>
    

Implementation Patterns

1. Service Container Integration

Pattern: Register the configured Environment as a singleton in Laravel’s container for reuse across controllers/services.

// In AppServiceProvider::boot()
app()->singleton('markdown.converter', function ($app) {
    $environment = Environment::createCommonMarkEnvironment();
    $environment->addExtension(new TableExtension());

    return new Converter(
        new DocParser($environment),
        new HtmlRenderer($environment)
    );
});

Usage:

// In a controller
$converter = app('markdown.converter');
$html = $converter->convert($markdownContent);

2. Blade Directives for Markdown Tables

Pattern: Create a Blade directive to render Markdown tables inline.

// In AppServiceProvider::boot()
Blade::directive('markdown', function ($expression) {
    return "<?php echo app('markdown.converter')->convert({$expression}); ?>";
});

Usage in Blade:

@markdown($markdownVariable)

3. API Response with Markdown Tables

Pattern: Convert Markdown to HTML in API responses (e.g., for documentation).

use Illuminate\Http\Response;

public function getDocumentation()
{
    $markdown = file_get_contents(storage_path('docs/api.md'));
    $html = app('markdown.converter')->convert($markdown);

    return response($html, 200)
        ->header('Content-Type', 'text/html');
}

4. Customizing Table Attributes

Pattern: Extend the HtmlRenderer to add custom attributes (e.g., class names).

use League\CommonMark\Renderer\Node\TableRenderer;

$environment = Environment::createCommonMarkEnvironment();
$environment->addExtension(new TableExtension());

// Custom renderer
$environment->addRenderer(new class extends TableRenderer {
    public function renderTable($node, NodeRendererInterface $htmlRenderer)
    {
        $htmlRenderer->getNodeData($node)->setAttribute('class', 'custom-table');
        return parent::renderTable($node, $htmlRenderer);
    }
});

5. Validation + Sanitization

Pattern: Sanitize Markdown input to prevent XSS (e.g., in user-generated content).

use League\CommonMark\Util\HtmlElement;

$environment = Environment::createCommonMarkEnvironment();
$environment->addExtension(new TableExtension());

// Sanitize HTML output
$html = app('markdown.converter')->convert($markdown);
$cleanHtml = preg_replace('/<[^>]*>/', '', $html); // Example: Strip all tags (use DOM for production)

6. Testing Markdown Tables

Pattern: Use PHPUnit to test table rendering.

public function testTableRendering()
{
    $markdown = "| Header | Data |\n|--------|------|\n| Row 1  | 123  |";
    $html = app('markdown.converter')->convert($markdown);

    $this->assertStringContainsString('<table>', $html);
    $this->assertStringContainsString('<th>Header</th>', $html);
}

Gotchas and Tips

1. Deprecation Warning

  • Issue: This package is deprecated and replaced by League\CommonMark\Extension\Table in league/commonmark ≥1.3.
  • Fix: Upgrade to league/commonmark:^1.3 and use:
    use League\CommonMark\Extension\Table\TableExtension;
    $environment->addExtension(new TableExtension());
    
  • Tip: Run composer update league/commonmark to migrate seamlessly.

2. Alignment Quirks

  • Issue: Alignment (:---, :--:, ---:) may not render as expected if the separator line has inconsistent spacing.
    | Left  | Center | Right |
    |:------|:------:|------:|  ❌ (Extra space after `:------`)
    
  • Fix: Ensure separators align perfectly with headers:
    | Left  | Center | Right |
    |:-----|:-----:|------:|  ✅
    

3. Nested Tables

  • Issue: Nested tables (tables inside cells) are not supported by GFM or this extension.
  • Workaround: Use HTML <table> directly in Markdown cells or flatten the structure.

4. Double Escaping Attributes

  • Issue: Fixed in v2.1.0, but older versions may double-escape HTML attributes (e.g., class="table" becomes class="&quot;table&quot;").
  • Fix: Upgrade to league/commonmark-ext-table:^2.1.0 or use the bundled extension.

5. Performance with Large Tables

  • Issue: Parsing very large tables (e.g., 1000+ rows) may impact performance.
  • Tip: Cache the Converter instance (Laravel’s service container handles this automatically) or pre-render tables to HTML.

6. Custom Styling Conflicts

  • Issue: Inline styles (e.g., style="text-align: center") may conflict with CSS frameworks like Bootstrap.
  • Fix: Use CSS classes instead:
    // In a custom renderer
    $htmlRenderer->getNodeData($node)->setAttribute('class', 'text-center');
    
    Then style with:
    .text-center { text-align: center; }
    

7. Debugging Parsing Errors

  • Tip: Enable CommonMark’s debug mode to inspect parsing issues:
    $environment->addExtension(new \League\CommonMark\Extension\DebugExtension());
    
    This adds debug comments to HTML output (e.g., <!-- DEBUG: Node type -->).

8. Extending for Advanced Features

  • Pattern: Subclass TableRenderer to add features like:
    • Row stripping: Remove empty rows.
    • Conditional rendering: Hide tables based on user roles.
    class CustomTableRenderer extends TableRenderer {
        public function renderTable($node, NodeRendererInterface $htmlRenderer)
        {
            if (auth()->user()->cannot('view-tables')) {
                return '';
            }
            return parent::renderTable($node, $htmlRenderer);
        }
    }
    
    Register it:
    $environment->addRenderer(new CustomTableRenderer());
    

9. Laravel Blade + Markdown Tables

  • Tip: Combine with laravel-markdown for Blade integration:
    composer require darkaonline/laravel-markdown
    
    Usage:
    {!! Markdown::parse($markdownWithTables) !!}
    

10. CommonMark Version Mismatches

  • Issue: Using league/commonmark-ext-table with an incompatible league/commonmark version (e
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament