What is the easiest way to add the code snippets to your blog post using Umbraco RTE

What is the easiest way to add the code snippets to your blog post using Umbraco RTE

Blog posts about software development always contain some kind of source code.

It would be very useful if I could add the source code as part of the blog post in a lightweight manner. To me, this means that I don't need to worry about the formatting, positioning, the actual language which I am using, etc.

My idea of the implementation is as follows:

Add the new Macro in Umbraco RTE, which will be called and should contain only one text area which shall persist the code snippet.

Add the https://highlightjs.org/ as a JavaScript library which will detect the code snippets and do the all hard work on the client side.

Umbraco preparation

Under the ~/Views/MacroPartials folder create the _CodeSnippet.cshtml file:

@inherits Umbraco.Web.Macros.PartialViewMacroPage


Log in to the Umbraco backend.

Open the Developers section.

Create a Macro called Code Snippet as in the screenshot below.

Define the MVC Partial view to point to the _CodeSnippet.cshtml which we defined previously.

Click on the Parameters tab and define the "Code" parameter like in the screenshot below.

Important part is: Wherever you have the RTE which should render the code snippets, you have to place the following code:

@Html.Raw(library.RenderMacroContent(Model.Text, Model.Content.Id))

Also, ensure that you have enabled needed tags (<pre> and <code>) in tinyMceConfig.config  in order to instruct Umbraco to save the content of the RTE properly without truncating the content.

In order to allow all elements, just define it like this:


Front-end preparation

In order to include the JavaScript library for rendering the code snippets using the proper languages we have to add this piece of code to the _Layout.cshtml or on the Template responsible for rendering the code snippet content.

<script src="/js/highlight.min.js"></script>

Please notice that we should include the highlight.min.js file to the project which can be found at the following link: https://github.com/isagalaev/highlight.js

See it in action :)

Note: The macro feature should be enabled for the Umbraco RTE

Just leave the cursor at the place wherever you'd like to add the code snippet.

Click on the macro icon.

Click the CodeSnippet macro:

Paste the prepared code to the Code Text Area.

Click submit, and the CodeSnippet will appear in the place where you left the cursor in the RTE.

After publishing the page, it will be rendered like in the below image.

Leave a Comment