Insert code samples to content (example)
Learn how to model and insert code samples in Kentico Kontent.
Table of contents
Create a content type for the code sample
The first step is to create a content type for your piece of code.
- From the app menu, choose Content models.
- Click Create new.
- Type Code sample in Content type name.
- Add a Text element for the code itself.
- Name it Code.
- Make it required.
- Add a Multiple choice element for selecting the code's programming language.
- Name it Language.
- Add options for every programming language you want to support.
- Set the element to show its options as Radio buttons.
- Make it required.
- Click Save changes.
The result can look similar to what you see in the image below.
Insert code sample in your content
When you have your code sample defined, you can add it in one of your texts as a component.
- From the app menu, choose Content & Assets.
- Open a content item with a rich text element.
- In the rich text, place your cursor to where you want to insert your code.
- On the editor toolbar, click Insert... and then Insert new component.
- Choose Code sample from the list of content types.
- Fill in the two elements.
Your code sample now exists as a component within the item you're editing.
From single-use to re-use
If you later find another use for the content in your component, you can always convert it to a content item by clicking Reuse as content item. This conversion cannot be undone. If done by accident, you can archive the new item and recreate your component.
After you finish typing the code, you can continue editing the content item. All changes are saved automatically.
You can create single-use code samples or reuse them in multiple places if needed. In any case, you need to make sure the code sample is displayed correctly within the text and add syntax highlight to improve readability.
- Teach your app how to deal with structure in rich text so that it can display your code samples. After that you can sprinkle a bit of a syntax highlighter such as PrismJSOpens in a new window to make it more appealing.
- Know when to use components instead of content items in rich text.
- Link your existing content together to build landing pages and more.