17 January 2023by Jack McGregor
Rendering code languages in stylish blocks, especially when served from a CMS like Payload, can be tricky. Using JAMstack, developers can use the triple backtick method to denote which language they want to use, and most Markdown compilers are smart enough to know the difference.
For example, the following is written in Markdown:
Which will render Javascript
But, like I said, rendering from a CMS can be awkward, as I found out writing this goddamn post.
So in this post, we're going to focus on two parts: the front-end, written in NextJS, and the backend, written with Payload.
Disclaimer: this post will not show you the NextJS or Payload configurations as it's out of scope
Let's start with PayloadCMS:
PayloadCMS
Payload can use something called Blocks when building content. The idea is that we break up our content - like code and text - into blocks, instead of using one to do the other (like using Rich Text to format with a code block, which may or may not work, and will always look shit.
Blocks belong in a sibling of /collections and ours will look a bit like this
The languages array is important - first it is the label and value which we'll use see in Payload, second its what the client needs to see (but we'll get to that later).
Next up is our Text Block, which will esentially be a Rich Text type in its own block
You can change this as you like, but its useful to be able to add media into it.
Once the blocks are created, you can add them to the resource's (in my case, Posts) fields array:
Once configured, we should be able to create an instance of content by selecting either CodeBlock or ContentBlock:

ContentBlock

CodeBlock

Drop in some code, select a language and away you go!
The following CodeBlock...

...will eventually be rendered like so:
NextJS
We all know that NextJS is extraordinarily powerful as is, but it really comes alive when mixed with other plugins.
Plugins like @mantine/prism - install following the instructions
In its most simple form, we take the language property we set on CodeBlock and use it to determine the language for our rendered code.
Step 1: Query the content
Make sure your GraphQL query has the correct fields
Once queried successfully, you should be using a serialiser to render your content, and its fairly straightforward to add the language to Prism
Once everything is set up successfully, you should be able to render any language of your choosing that Prism supports (Tip: you can actually add languages eg HTML to the Payload list, but be careful).
You should hopefully be able to render multiple code blocks of varying languages in a funky blog post!
Thanks for reading!
Bash
HTML
SCSS
GraphQL
JSON
Playwright ID scraper31 January 2023Seed file for PayloadCMS23 January 2023Creating dynamic test IDs for Jest and Playwright17 January 2023