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

alten/syntax-highlight-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

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

    Add to AppKernel.php:

    new Alten\SyntaxHighlightBundle\AltenSyntaxHighlightBundle(),
    

    Run asset installation:

    php bin/console assets:install
    
  2. First Use Case: Add the bundle's JS/CSS to your base Twig template (e.g., base.html.twig):

    <!-- Include core scripts -->
    <script src="{{ asset('bundles/altensyntaxhighlight/js/scripts/shCore.js') }}"></script>
    <script src="{{ asset('bundles/altensyntaxhighlight/js/scripts/shAutoloader.js') }}"></script>
    
    <!-- Include theme CSS -->
    <link rel="stylesheet" href="{{ asset('bundles/altensyntaxhighlight/css/styles/shCoreMidnight.css') }}">
    <link rel="stylesheet" href="{{ asset('bundles/altensyntaxhighlight/css/styles/shThemeMidnight.css') }}">
    
    <!-- Initialize highlighter -->
    <script>SyntaxHighlighter.all();</script>
    
  3. Basic Syntax Highlighting: Use <pre> tags with brush: class in your Twig templates:

    <pre class="brush: php">
    <?php
    echo "Hello, World!";
    ?>
    </pre>
    

Implementation Patterns

1. Dynamic Language Detection

  • Use Twig extensions or PHP logic to dynamically assign the brush: class based on file extensions (e.g., .php, .js, .sql).
  • Example Twig filter:
    {% macro highlight(code, language) %}
      <pre class="brush: {{ language }}">
        {{ code|e('html_attr') }}
      </pre>
    {% endmacro %}
    
    Usage:
    {{ _self.highlight(code, 'python') }}
    

2. Lazy Loading for Performance

  • Load only required brushes (e.g., shBrushPhp.js) instead of all scripts. Update shAutoloader.js to exclude unused languages:
    // In a custom JS file
    SyntaxHighlighter.autoloader.apply(null, [
      'shBrushPhp', 'shBrushJs', 'shBrushCss'
    ]);
    

3. Integration with CMS/Editor

  • For WYSIWYG editors (e.g., TinyMCE, CKEditor), use a custom plugin to wrap code blocks in <pre class="brush: ..."> tags. Example:
    // TinyMCE plugin example
    tinymce.PluginManager.add('syntaxhighlight', function(editor) {
      editor.addButton('highlight', {
        text: 'Highlight',
        onclick: function() {
          editor.insertContent('<pre class="brush: js">\n// Your code\n</pre>');
        }
      });
    });
    

4. Server-Side Highlighting (Fallback)

  • Use PHP libraries (e.g., GeSHi) as a fallback for non-JS environments:
    {% if app.environment == 'prod' %}
      {{ include('highlight_fallback.html.twig', { code: code, language: language }) }}
    {% else %}
      {{ _self.highlight(code, language) }}
    {% endif %}
    

5. Custom Themes

  • Override default themes by copying CSS files from vendor/alten/syntax-highlight-bundle/Resources/public/css/styles/ to web/bundles/altensyntaxhighlight/css/styles/. Customize colors in your project’s SCSS/Less.

Gotchas and Tips

Pitfalls

  1. Asset Paths in Production:

    • After assets:install, verify paths in app/config/config_prod.yml or use asset() in Twig. Hardcoding paths (e.g., /bundles/...) breaks in production.
  2. Missing Brushes:

  3. JavaScript Errors:

    • Ensure shCore.js and shAutoloader.js are loaded before any brush scripts. Use defer or place scripts at the bottom of <body>.
  4. Twig Autoescaping:

    • Use |e('html_attr') or |raw when embedding dynamic code to avoid XSS or broken syntax:
      <pre class="brush: {{ language }}">{{ code|raw }}</pre>
      
  5. Caching Issues:

    • Clear cache after updating assets:
      php bin/console cache:clear --env=prod
      php bin/console assets:install --symlink --env=prod
      

Debugging Tips

  • Check Console: Open browser DevTools (F12) to verify JS errors (e.g., SyntaxHighlighter is not defined).
  • Validate HTML: Ensure <pre> tags are properly nested and class="brush: ..." is correctly formatted.
  • Test in Isolation: Temporarily disable other JS/CSS to rule out conflicts.

Extension Points

  1. Add Custom Brushes:

  2. Override Default Config:

    • Extend shCore.js by including a custom config file:
      <script src="{{ asset('bundles/altensyntaxhighlight/js/scripts/shCore.js') }}"></script>
      <script src="{{ asset('js/custom-sh-config.js') }}"></script>
      
      Example custom-sh-config.js:
      SyntaxHighlighter.defaults['gutter'] = false;
      SyntaxHighlighter.defaults['toolbar'] = false;
      
  3. Server-Side Preprocessing:

    • Use a Twig extension to pre-process code blocks (e.g., trim whitespace) before rendering:
      // src/AppBundle/Twig/HighlightExtension.php
      public function highlightCode($code, $language) {
          return str_replace("\r\n", "\n", trim($code));
      }
      
      Register in services.yml:
      services:
          app.twig.highlight_extension:
              class: AppBundle\Twig\HighlightExtension
              tags: ['twig.extension']
      
  4. Webpack/Encore Integration:

    • For modern Laravel apps, import JS/CSS via Webpack:
      // webpack.config.js
      Encore
        .addEntry('syntax-highlight', './assets/js/syntax-highlight.js')
        .copyFiles({
          from: './vendor/alten/syntax-highlight-bundle/Resources/public',
          to: 'bundles/altensyntaxhighlight/[path][name].[ext]',
        });
      
      Then include the entry point in your layout:
      {{ encore_entry_link_tags('syntax-highlight') }}
      
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