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 Table Extension Laravel Package

webuni/commonmark-table-extension

Deprecated: GitHub-Flavored Markdown table support for league/commonmark. Functionality is now bundled in league/commonmark 1.3+ as League\CommonMark\Extension\Table—upgrade and use the built-in TableExtension for parsing/rendering tables.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Replace with Built-in Extension: Since this package is deprecated, migrate to league/commonmark v1.3+ (bundled Table extension). Update composer.json:

    "league/commonmark": "^1.3"
    

    Then configure the environment:

    use League\CommonMark\Environment;
    use League\CommonMark\Extension\Table\TableExtension;
    
    $env = Environment::createCommonMarkEnvironment();
    $env->addExtension(new TableExtension());
    
  2. First Use Case: Test with a simple GFM table in a Blade template or controller:

    | Syntax      | Description |
    |-------------|-------------|
    | Header      | Title       |
    | Paragraph   | Text        |
    

    Render via:

    $converter = new Converter(new DocParser($env), new HtmlRenderer($env));
    echo $converter->convertToHtml($markdown);
    
  3. Key Files to Review:

    • config/commonmark.php (if using Laravel’s spatie/laravel-markdown).
    • Migration guide for league/commonmark v1.3 changelog.

Implementation Patterns

Core Workflows

  1. Laravel Integration:

    • Service Provider: Bind the converter in AppServiceProvider:
      public function boot()
      {
          $env = Environment::createCommonMarkEnvironment();
          $env->addExtension(new TableExtension());
          $this->app->singleton(Converter::class, fn() => new Converter(
              new DocParser($env),
              new HtmlRenderer($env)
          ));
      }
      
    • Blade Directives: Create a custom directive for Markdown-to-HTML:
      Blade::directive('markdown', function ($expression) {
          $converter = app(Converter::class);
          return "<?php echo {$expression}->convertToHtml(" . $expression . "); ?>";
      });
      
      Usage:
      @markdown($content)
      
  2. Dynamic Table Styling: Extend the HtmlRenderer to customize table classes/attributes:

    $renderer = new HtmlRenderer($env);
    $renderer->getNodeRendererRegistry()->addRenderer(
        TableSection::class,
        new class extends TableSectionRenderer {
            public function render(TableSection $table, RenderContext $context): string {
                $html = parent::render($table, $context);
                return str_replace('<table', '<table class="custom-table"', $html);
            }
        }
    );
    
  3. API Documentation: Parse API response tables from Markdown:

    $markdown = <<<MD
    | Endpoint       | Method | Description          |
    |----------------|--------|----------------------|
    | `/users`       | GET    | List all users       |
    MD;
    $html = $converter->convertToHtml($markdown);
    
  4. CMS Content: Store Markdown with tables in a database (e.g., content column) and render dynamically:

    $post = Post::find(1);
    $html = $converter->convertToHtml($post->content);
    return view('posts.show', compact('html'));
    

Advanced Patterns

  • Table Captions: Use MultiMarkdown syntax for captions:

    | Name  | Age |
    |-------|-----|
    | Alice | 30  |
    [*Users*][users-table]
    

    Rendered as:

    <table>
      <caption id="users-table">Users</caption>
      <!-- table content -->
    </table>
    
  • Alignment Control: Leverage GFM alignment syntax (:---, :--:, ---:) for left/center/right alignment:

    | Left-Aligned  | Center-Aligned | Right-Aligned |
    |:-------------|:--------------:|--------------:|
    | Left         | Center         | Right         |
    
  • Nested Tables: Supported natively (though visually limited in HTML):

    | Outer Table |
    |-------------|
    |             |
    | | Inner     | |
    | | Table     | |
    | |-----------|
    | | Cell 1.1  | |
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • This package is archived. Always use league/commonmark’s built-in TableExtension (v1.3+).
    • Migration Step: Replace:
      use League\CommonMark\Ext\Table\TableExtension;
      
      with:
      use League\CommonMark\Extension\Table\TableExtension;
      
  2. Double Escaping:

    • Fixed in v2.1.0, but older versions may escape HTML attributes twice. Ensure you’re on the latest league/commonmark version.
  3. Alignment Quirks:

    • Right alignment requires trailing colons (---:), not leading. Test edge cases like single-column tables:
      | Right |
      |------:|
      | 123   |
      
  4. Caption Limitations:

    • Captions must be on the line after the table body (not before the header). Example:
      | A | B |
      |---|---|
      | 1 | 2 |
      [*Caption*][ref]
      
  5. Performance:

    • Parsing large tables (e.g., 100+ rows) may impact performance. Benchmark with league/commonmark’s bundled extension.

Debugging Tips

  1. Malformed Tables:

    • Use league/commonmark's InlineParser to debug syntax errors:
      $parser = new InlineParser($env);
      $document = $parser->parse($markdown);
      // Inspect $document for errors
      
  2. HTML Output Issues:

    • Override the HtmlRenderer to log raw HTML:
      $renderer = new HtmlRenderer($env);
      $renderer->getNodeRendererRegistry()->addRenderer(
          TableSection::class,
          new class extends TableSectionRenderer {
              public function render(TableSection $table, RenderContext $context): string {
                  $html = parent::render($table, $context);
                  Log::debug('Table HTML:', ['html' => $html]);
                  return $html;
              }
          }
      );
      
  3. Alignment Not Rendering:

    • Verify the text-align style is applied in the rendered HTML. If missing, check for CSS conflicts or custom renderer overrides.

Extension Points

  1. Custom Renderers: Extend TableSectionRenderer to modify table structure:

    class CustomTableRenderer extends TableSectionRenderer {
        public function render(TableSection $table, RenderContext $context): string {
            $html = parent::render($table, $context);
            return str_replace('<table', '<table data-custom="true"', $html);
        }
    }
    

    Register it:

    $renderer->getNodeRendererRegistry()->addRenderer(
        TableSection::class,
        new CustomTableRenderer()
    );
    
  2. Preprocessing Markdown: Use Laravel’s Str::of() or regex to transform tables before parsing:

    $markdown = Str::of($input)
        ->replaceMatches('/\|(.*)\|/', '| **$1** |') // Bold headers
        ->toString();
    
  3. Post-Processing HTML: Use DOMDocument to modify the rendered HTML:

    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $tables = $dom->getElementsByTagName('table');
    foreach ($tables as $table) {
        $table->setAttribute('class', 'data-table');
    }
    $cleanHtml = $dom->saveHTML();
    

Configuration Quirks

  1. Laravel Cache: If using spatie/laravel-markdown, clear the cache after enabling the TableExtension:

    php artisan cache:clear
    
  2. Environment Order: Extensions must be added before the converter is instantiated. Order matters for conflicts:

    $env = Environment::createCommonMarkEnvironment();
    $env->addExtension(new TableExtension()); // Must be first
    $env->addExtension(new YourCustomExtension());
    
  3. PHP Version: Requires PHP 7.1+. Use composer require league/commonmark:^1.3 to auto-resolve dependencies.

Pro Tips

  1. Test with Edge Cases: Validate these table types:
    • Single-cell tables.
    • Tables with merged cells (limited support; consider CSS for visual merging).
    • Nested tables (3+ levels deep).
    • Tables with Markdown inside cells (e.g
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity