01Article · blog post
Draft

How to do code syntax highlighting

This as an internal guide to writing code snippets in Contentful

02Content

Code snippets are created using code formatting in Contentful and can be inline or span multiple lines (in which case use Shift+Enter to create line-breaks within a code block).

Syntax highlighting is implemented using highlight.js. The programming language is inferred automatically if no language hint is provided. E.g.:

def myFunction: print('This is some Python code')

It is recommended to provide an explicit language hint, which can be done by including `lang=<code> as the first line. E.g. the following code block starts with `lang=ts:

import { CommonModule, NgModule } from '@angular/core'; @NgModule({ imports: [CommonModule], }) export class SomeModule {}

In addition to setting the language, the same syntax can be used to provide a caption for the code snippet (by including another line with `caption=Some descriptive caption):

package main import "fmt" func main() { fmt.Println("Hello, 世界") }

Some descriptive caption

There is also a shorthand available for when a snippet should be captioned with a file name. E.g. in the next snippet it's enough to only specify `file=src/greet.js (the language is determined by the file extension):

const greet = name => { console.log(`Hello, ${name}!`); };

src/greet.js

The implementation is not set in stone, so let us know if you have any trouble formatting code or want to suggest some changes 🙂




More examples

const greet = (name: string): string => { console.log(`Hello, ${name}!`); };

Greet but in TypeScript


.burger-menu { width: 28px; height: 2px; position: relative; transition: transform 0.2s; } /* comment */ .burger-menu .burger-line { display: block; left: 0; width: calc(100% - 34px); }

simple.css


.burger-menu { width: $width; height: $some-height; position: relative; transition: transform $transition-time; /* comment */ .burger-line { display: block; left: 0; width: calc($height - 34px); } }

simple.scss


@import url(https://fonts.googleapis.com/css?family=Questrial); @import url(https://fonts.googleapis.com/css?family=Arvo); @font-face { src: url(https://lea.verou.me/logo.otf); font-family: 'LeaVerou'; } /* Shared styles */ section h1, #features li strong, header h2, footer p { font: 100% Rockwell, Arvo, serif; }

Simple SCSS


{ "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 27, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "children": [], "spouse": null }

03Continue reading
See all articles