Structured Text, adding syntax highligting to code tags

I’m using Structured Text inside a nuxt app.

I’m trying to add prism.js to add code syntax highlighting. The thing is I need to add a class name to the code tags specific to the language, like this guide shows.

I’m trying to figure out how to add a custom rendering to code blocks and can’t find any good documentation about it.

Hey @awdriggs, did you already see the vue-datocms repo readme on that?

If not, that might be a good place to start? If that didn’t work for you, could you please share some sample code?

Thanks! I used that as a starting point and got something working. Posting it below for anyone else to reference. Also would appreciate any comments if I’m doing anything stupid or crazy here.

Here is my custom renderer for the code blocks

const customNodeRules = [
  //render rule for if the node is code
  renderNodeRule(isCode, ({ node }) => {
    return h(SyntaxHighlight, { //use the syntaxHighlight component with the data
      code: node.code, //props for the component
      language: node.language,
    }, () => []);
  })
];

Here is the template part…

<datocms-structured-text :data="article.body" :renderBlock="renderBlock" :customNodeRules="customNodeRules"  class="content"/>

And here is the SyntaxHighlight component that uses prism

<script setup>

defineProps(['code', 'language', 'showLineNumbers']) //props being based to this component

import { onMounted } from 'vue';
import Prism from "prismjs";
import "prismjs/themes/prism.min.css";

//highlight when the component is mounted.
onMounted(() => {
  Prism.highlightAll();
});
</script>

<template>
  <pre><code :class="'language-'+language">{{code}}</code></pre>
</template>
1 Like