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

Syntax Highlight Bundle Laravel Package

adiog/syntax-highlight-bundle

Symfony bundle that packages Alex Gorbatchev’s SyntaxHighlighter 3.0.83 for Composer-based apps. Install via composer, enable the bundle in AppKernel, then run assets:install to publish the JS/CSS for client-side code highlighting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require adiog/syntax-highlight-bundle:dev-master
    

    Add the bundle to app/AppKernel.php:

    new Adiog\SyntaxHighlightBundle\SyntaxHighlightBundle(),
    
  2. Install Assets:

    php bin/console assets:install --symlink
    

    This symlinks the required JS/CSS files (shCore.js, shTheme*.css) from vendor/adiog/syntax-highlight-bundle/Resources/public/ to web/bundles/adiog/.

  3. First Use Case: Embed code in a Twig template with syntax highlighting:

    {{ syntax_highlight(code, 'php') }}
    

    Where code is a string (e.g., $code = '<?php echo "Hello"; ?>';).


Where to Look First

  • Twig Extension: Check Adiog\SyntaxHighlightBundle\Twig\SyntaxHighlightExtension for available filters/tags.
  • Default Themes: The bundle includes themes like Default, Dracula, or Eclipse. Override in config.yml:
    adiog_syntax_highlight:
        theme: 'Dracula'
    
  • Supported Languages: The underlying SyntaxHighlighter supports languages like php, javascript, css, sql, etc. (see original docs).

Implementation Patterns

Workflows

  1. Dynamic Code Highlighting:

    • Pass raw code strings to Twig:
      {% set code = 'function foo() { return "bar"; }' %}
      <pre>{{ syntax_highlight(code, 'javascript') }}</pre>
      
    • Use with controller-passed data:
      return $this->render('page.html.twig', ['code' => $rawCode]);
      
  2. Reusing Highlighted Code:

    • Cache highlighted snippets in a service or database to avoid reprocessing:
      // src/Service/CodeCache.php
      class CodeCache {
          public function getHighlighted(string $code, string $lang): string {
              // Implement caching logic (e.g., Redis, filesystem).
          }
      }
      
  3. Custom Themes:

    • Override the default theme by copying Resources/public/shTheme*.css to your assets and updating the config:
      adiog_syntax_highlight:
          theme_path: '%kernel.root_dir%/../web/css/custom-theme.css'
      
  4. Integration with Markdown:

    • Use with a Markdown parser (e.g., php-markdown) to highlight code blocks:
      $markdown = new Markdown();
      $html = $markdown->transform($text);
      // Post-process to highlight code blocks with syntax_highlight.
      

Integration Tips

  • Asset Management:

    • For production, manually copy assets to web/ to avoid symlink issues:
      mkdir -p web/bundles/adiog
      cp -r vendor/adiog/syntax-highlight-bundle/Resources/public/* web/bundles/adiog/
      
    • Exclude from versioning in .gitignore:
      /web/bundles/adiog/
      
  • Lazy Loading:

    • Defer JS/CSS loading until a page with code is rendered:
      {% if codeBlocks|length > 0 %}
          {{ parent() }} {# Load assets via parent template #}
      {% endif %}
      
  • API Responses:

    • Highlight code in JSON API responses (e.g., for IDE plugins):
      return new JsonResponse([
          'code' => $highlightedCode,
          'language' => 'php',
      ]);
      

Gotchas and Tips

Pitfalls

  1. Asset Paths:

    • If assets aren’t installed, the highlighter fails silently. Always run assets:install post-install.
    • Fix: Add a post-install script to composer.json:
      "scripts": {
          "post-install-cmd": [
              "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
              "Adiog\\SyntaxHighlightBundle\\Composer\\InstallAssets::postInstall"
          ]
      }
      
  2. Language Mismatches:

    • Incorrect language parameters (e.g., 'php5' instead of 'php') may break highlighting.
    • Fix: Validate languages against the supported list.
  3. Twig Filter vs. Function:

    • The bundle provides both syntax_highlight filter and function. Use the filter for inline highlighting:
      {{ code|syntax_highlight('php') }} {# Filter #}
      {{ syntax_highlight(code, 'php') }} {# Function #}
      
  4. Deprecated Bundle:

    • The underlying SyntaxHighlighter (v3.0.83) is 14 years old and lacks modern features (e.g., ES6, TypeScript).
    • Workaround: Use a modern alternative (e.g., highlight.js) if needed, but this bundle may suffice for legacy codebases.

Debugging

  1. Broken Highlighting:

    • Check the browser’s Network tab for 404s on shCore.js or theme CSS.
    • Verify the theme config points to a valid file.
  2. Console Errors:

    • If JS fails, ensure shCore.js is loaded after jQuery (required by the highlighter):
      {{ parent() }} {# Loads assets in correct order #}
      
  3. Twig Errors:

    • Ensure the Twig extension is registered. Add this to config.yml if missing:
      twig:
          globals:
              syntax_highlight: '@adiog_syntax_highlight.twig.syntax_highlight'
      

Extension Points

  1. Custom Languages:

    • Extend the highlighter by adding custom brushes. Copy shBrush*.js from the original library to your bundle’s Resources/public/ and update the config:
      adiog_syntax_highlight:
          custom_brushes: ['shBrushCustom.js']
      
  2. Pre/Post-Processing:

    • Override the Twig extension to add logic (e.g., auto-detect language):
      // src/Adiog/SyntaxHighlightBundle/Twig/ExtendedSyntaxHighlightExtension.php
      class ExtendedSyntaxHighlightExtension extends \Adiog\SyntaxHighlightBundle\Twig\SyntaxHighlightExtension {
          public function getSyntaxHighlightedCode($code, $language = null) {
              if (null === $language) {
                  $language = $this->detectLanguage($code);
              }
              return parent::getSyntaxHighlightedCode($code, $language);
          }
      }
      
      Register it in services.yml:
      services:
          adiog_syntax_highlight.twig.syntax_highlight:
              class: Adiog\SyntaxHighlightBundle\Twig\ExtendedSyntaxHighlightExtension
              tags: ['twig.extension']
      
  3. Configuration Overrides:

    • Use environment-specific configs (e.g., config_dev.yml) to switch themes:
      adiog_syntax_highlight:
          theme: '%kernel.debug% ? Default : Dracula'
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky