Getting started
Let’s create a new Maizzle project../example-syntax-highlight, and select the Default Starter.
Choose Yes when prompted to Install dependencies.
Once it finishes installing dependencies open the project folder in your favorite code editor.
We’ll be covering two different techniques:
- with PostHTML
- with Markdown
PostHTML
Using a PostHTML plugin, we can write our own<pre><code> markup and have the plugin highlight the contents of the <code> element.
Install plugin
First, let’s install the posthtml-prism plugin, which we’ll use to highlight code blocks:config.js:
config.js
Add code block
Add a block of code in your template, like so:emails/example.html
Notice how we added the
language-javascript class on the <code> tag - this is required in order to get language-specific syntax highlighting.Build
Runnpm run dev to start the development server, open http://localhost:3000/ in a browser, and navigate to the template.
You’ll see something like this:
<span> tags. This means it worked, and PrismJS has tokenized our code block.
But it’s not very pretty, is it? We need a theme!
Theming
Choose one of the default themes, or see prism-themes for more. For this tutorial, we’ll go with a Tailwind adaptation the Synthwave ‘84 Theme. Save prism-synthwave84.css to thecss directory in your project, and import it into your css/tailwind.css:
npm run build will yield the result we expected.
Markdown
Alternatively, we can also use Markdown to write fenced code blocks and have PrismJS automatically syntax-highlight them.Install PrismJS
First, we must install the PrismJS library:Configure Markdown
Next, we need to configure Maizzle to use PrismJS as a custom highlight function for the Markdown renderer. We do that inconfig.js:
config.js
Fenced code block
We can now write code inside a fenced code block in our Template:emails/example.html
Compatibility
Some email clients require extra steps in order to render our code blocks properly.Gmail
Gmail will change our inlinewhite-space: pre; to white-space: pre-wrap;. This results in code wrapping, instead of showing a horizontal scrollbar.
Fix it by adding the following CSS at the beginning of prism-synthwave84.css:
css/prism-synthwave84.css
Outlook
Padding on<pre> doesn’t work in Outlook.
We can fix this by wrapping <pre> inside a table that we only show in Outlook. We then style this table inline, like so:
emails/example.html
Production build
We’ve been developing locally so far, configuring PostHTML or Markdown inconfig.js. This means CSS isn’t inlined, and most email optimizations are off.
When you’re satisfied with the dev preview, run npm run build and use the template inside the build_production/ directory for sending the email.
Resources
- GitHub repository for this tutorial
- posthtml-prism plugin
- PrismJS library
- Synthwave ‘84 theme