What is the easiest way to add the code snippets to your blog post using Umbraco RTE
Wednesday, May 16, 2018
By Jovica Turcinovic
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.
Under the ~/Views/MacroPartials folder create the _CodeSnippet.cshtml file:
@inherits Umbraco.Web.Macros.PartialViewMacroPage <pre> <code> @Model.MacroParameters["Code"] </code> </pre>
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:
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:
<validElements> <![CDATA[*[*]]]> </validElements>
<script src="/js/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</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.