For anyone that needs to share code, you know how important it is to communicate it in the right way. Just copying and pasting code into a blog post just won't do. Today we'll walkthrough how you can insert code into your blog posts to share with readers, and make it easy for them to read.
There are two distinct ways of sharing your code within a blog post. Let's dive in to each separately:
Sharing Code Method 1: HTML, CSS, JavaScript, Etc.
- Go to your blog post and select the Source Code icon (). Note: You need to utilize encoded characters (< and gt;) in this method.
- Find a place within the post where you want to insert code, and write <code> into the editor, such as in the image below. After inserting <code> a closing tag (</code> will automatically be added. Insert your source code between these tags.
- When done adding code, simply click the blue "Save" button in the lower left, and your post will be updated to include the code you added.
Sharing Code Method 2: HubL
If the code you are sharing includes HubL, HubSpot's Markup Language, then the editors by default will look to run that code. To prevent this from happening (and accurately display the code within the post) we need to add: to the beginning of the post and to the end of the post.
Using the above source code example, it would look something like this:
By adding these values to the top and bottom of your post, it escapes any HubL within the post and does not try to execute it.
You can also style code inserted into a blog post. If you have a really long code snippet, but don't want it to take over the entire post, similar to the blog post about How to Implement a Mega Menu on the COS, you can separate the code into blocks by adding:
<pre style="max-height:500px;"><code>Paste in code block here</code></pre>
This will limit the size of the code block and help your visitor read through the post.
If you are looking to highlight a specific syntax, you can also use a syntax highlighter such as Prism.js that will allow you to add a class to the <pre> and will automatically wrap your code in sample markup so you can style the highlighted version.
If you have any questions, or any other ways you've done this, let us know in the comments.