How to Prevent Code Snippets from Execution
Updated at: 20 July 2023Deepak PainkraIn this article, I will show you how you can create a code block using HTML and CSS, we will be using pre & code tags, but we will sanitize it first so it won't get executed,
How to Prevent Code Snippets from Execution?
To prevent the execution of the code, we will add < and >, so it will consider as text.
It is essential because it prevents your code base from cross-site scripting, but manually adding this into your code snippet is a bit harder and will consume too much time.
Adding < and > to Code Blocks,
To add this one to your code, then go ahead and heads over to the Tinymce website, where you can find this rich text editor.
If you paste your code into the sample code section, it will automatically add < and > to your code base, and now your code is ready to use,
What to do if I'm using a JSON Object?
The same approach will work, only format your code by using the JSON escape formator,
In case you want to do it manually, then paste your code into the browser URL section, and add Back Slash n to escape the new lines characters,
How to highlight code Snippet?
To highlight a code snippet, you can use the prism.js library,
Install the prism.js library by issuing this command,
You can read their documentation to implement into your code base,
import { useEffect } from 'react'
import React from 'react'
import "prismjs/themes/prism-tomorrow.css";
import Prism from "prismjs";
const Demo = ({post}) => {
useEffect(() => {
const highlight = async () => {
await Prism.highlightAll(); // <--- prepare Prism
};
highlight(); // <--- call the async function
}, [post]);
return (
<div>{post.content}</div>
)
}
export default Demo
and if you are using NextJS, this is how you can highlight syntax,
Support Us
Your support helps us continue our work. Please consider making a donation.
Donate with PayPal