Syntax highlighting with prism.js for your Laravel application

Jun 11, 2022 by Thibault Debatty | 3530 views

Laravel

https://cylab.be/blog/222/syntax-highlighting-with-prismjs-for-your-laravel-application

Prism is a light and easy javascript library that allows to integrate code highlighting in your web application. Here is how to install and use it with Laravel...

prismjs.png

Installation

npm install prismjs

We will use the prismjs babel plugin to select the plugins, languages and themes that will be loaded. This allows to load only required code:

npm install babel-plugin-prismjs

In resources/js/app.js, load prismjs:

# prismjs
# https://cylab.be/blog/222/syntax-highlighting-with-prismjs-for-laravel
import Prism from 'prismjs';

Create a file called .babelrc where you can list what must be loaded.

{
  "plugins": [
    ["prismjs", {
        "languages": ["php", "javascript", "css"],
        "plugins": [],
        "theme": "coy",
        "css": true
    }]
  ]
}

In the example above, we enable syntax highlighting for php, javascript and css. You can find the complete list of supported languages and plugins on the website of prism.js: https://prismjs.com/#supported-languages

You can now rebuild your javascript code:

npm run prod

Usage

To enable code highlighting, simply wrap your code block with a <pre> and a <code>, with a class indicating the language:

<pre><code class="language-css">p { color: red }</code></pre>

This will produce something like:

p { color: red }

Attention: You have to escape all < and & characters inside your code blocks, otherwise the browser might interpret them as an HTML tags or entities.

This blog post is licensed under CC BY-SA 4.0