Syntax highlighting for your Symfony app with prismjs

Gregor Nobis
3 min readAug 25, 2023

--

So, you wrote some code and you want to show it to the world. In verbatim that is. While you app’s code does useful things it is never visible. Time to publish some code or code examples to show off how good you are at hiding puns in comments.

Now you need to figure out two things:

  • What is the best solution for syntax highlighting code for the web?
  • How do you install it in your Symfony based application?

These are easily answered.

The best library is prismjs

Check it out at prismjs.com

Prism has everything you need. Multiple themes and covers practically any programming language you culd possibly know. Comment if you are proficient in a language they don’t support. I’d be curious to know.

Installing it in Symfony is really easy

1 — Add the package to your dependencies.

If you are managing dependencies using npm:

$ npm install prismjs

Or, if you are using yarn:

$ yarn add prismjs

This wasn’t surprising.

2 — Add the css and js for prism to your app html output

One way is to hard code the dependencies into the html head of your app:

<head>
...
<link href="primsjs/themes/prism.css" rel="stylesheet" />
</head>
<body>
...
<script src="prism.js"></script>
</body>

Make sure the paths are correct. The second and better option is to include them automatically in your build step.

So, in your app.js file add this:

import 'prismjs/themes/prism.css';
require('prismjs');

Ok, but still nothing to see. So now let’s add some code to a template and highlight it using prismjs.

3 — Add the markup for your code

Here’s a boring example. In your page html template add this:

<div>
A block of highlighted Code
<pre>
<code class="language-css">
p { color: red }
</code>
</pre>

An inline code snippet works like this:
<code class="language-css">p { color: red }</code>
Looks good, too.
</div>

And boom there it is:

Rendered output for the above code highlighting example

4 — Avoid trouble

Make sure you escape all < and & characters in your code, otherwise this might break rendering in the browser.

5 — Tweak and choose your theme

  • Use minified css code to save on page size
  • Choose a theme. Prismjs comes with various themes, you can preview them on their site. To change your highlighted code appearance simply import a different theme.

With both changes combined you’d replace

'prismjs/themes/prism.css'

with

'prismjs/themes/prism-tomorrow.min.css'

And that is it.

That’s a wrap

Now you know how to install prismjs in your Symfony application. And probably learned how to install many others because the basics are the same.

While you are here, why don’t you check out my latest product, it’s an API to identify and block temporary email addresses.

--

--