Skip to content
Last updated

Code snippet tag

Plans:ProScaleEnterprise

The code-snippet tag displays code examples in your documentation that are loaded from local files.

Syntax and usage

The code-snippet tag is a self-closing tag, which means it has no child elements. Use attributes to pass the path to the local file and configure how the snippet is displayed.

Code:
{% code-snippet
  file="./code-examples/museum-config.yaml"
  language="yaml"
  from=1
  to=10
  title="museum-redocly.yaml"
/%}
Result:
museum-redocly.yaml
products:
  tickets:
    name: Museum Tickets
    icon: images/ticket-logo.png
    folder: products/tickets/
  events:
    name: Museum Events
    icon: ./images/event-logo.svg
    folder: ./products/events
navbar:

Attributes

OptionTypeDescription
filestringThe absolute or relative path to the file with the code snippet.
fromnumber | stringUse to specify the starting point of your code snippet and include it in the rendered element. Works with either a line number or a specific string contained in the starting line. Mutually exclusive with after.
tonumber | stringUse to specify the ending point of your code snippet and include it in the rendered element. Works with either a line number or a specific string contained in the starting line. Mutually exclusive with before.
afternumber | stringSimilar to from but excludes the starting point from the rendered element. Mutually exclusive with from.
beforenumber | stringSimilar to to but excludes the ending point from the rendered element. Mutually exclusive with to.
prefixstringUse to add explanatory information at the start of the code snippet. Prepend with // to style as a comment. Redocly recommends including a new line (\n) at the end of the prefix.
languagestringSets the syntax highlighting rules for the code sample used. Syntax highlighting is available for all supported languages.
titlestringSet the text displayed in the gray header at the top of the code snippet.Commonly used for filenames.
wrapbooleanWraps long lines in the code snippet to avoid or reduce horizontal scroll. Default: false.
previewLinesnumberThe number of lines the code snippet displays before a Show more button. A snippet with the same number of lines or fewer is displayed in full. Set to 0 to always display the snippet in full. Must be a whole number of 0 or more, otherwise the attribute is ignored. Default: the previewLines value in redocly.yaml or the page's front matter.

Supported languages

The following table lists the values that enable syntax highlighting. Each value selects a language grammar, and its aliases select the same grammar.

NameValueAliases
Bashbashshell, sh, zsh, shellscript, curl
C (both C and C++ use the C grammar)cc++, cpp
CoffeeScriptcoffeecoffeescript
C#csharpc#, cs, c#+newtonsoft
CSScss
Gogo
GraphQLgraphqlgql
HTMLhtml
HTTPhttp
Javajavajava8+apache
JavaScriptjavascriptjs, cjs, mjs, node.js
JSONjson
JSON Seqjson-seqapplication/json-seq
JSONLjsonl
Kotlinkotlinkt, kts
Lualua
Markdocmarkdoc
Markdownmarkdownmd
Multipart mixedmultipart-mixedmultipart/mixed
Objective-Cobjective-cobjectivec, objc
Perlperl
PHPphp
Pythonpythonpy
Rubyrubyrb
Scalascala
SQLsql
Swiftswift
Tree viewtreeview
TSXtsxjsx
TypeScripttypescriptts, cts, mts
Vimvimviml, vimscript
XMLxml
YAMLyamlyml

Use text for plain, unformatted text. Unsupported language names also fall back to text.

Examples

Use line numbers as selectors

Code:
{% code-snippet
  file="./code-examples/museum-config.yaml"
  language="yaml"
  from=11
  to=16
  title="museum-redocly.yaml"
  prefix="// Please reserve navbar entries for important use cases \n"
/%}
Result:
museum-redocly.yaml
// Please reserve navbar entries for important use cases 
  items:
    - page: about-the-museum.md
      label: About
    - page: sponsor-the-museum.md
      label: Benefactors
footer:

Use strings as selectors

Code:
{% code-snippet
  file="./code-examples/museum-config.yaml"
  language="yaml"
  from="footer"
  to="redirects"
  title="museum-redocly.yaml"
/%}
Result:
museum-redocly.yaml
footer:
  copyrightText: Redocly Museum API
  items:
    # Column 1
    - page: policies/faq.md
      label: Museum FAQ
    # Column 2
    - group: Resources
      items:
        - href: https://access.si.edu/museum-professionals
          label: Smithsonian Resources
        - href: https://www.aam-us.org/topic/resource-library/
          label: American Alliance of Museums
redirects:

Compare selection attributes

Using the to / from selectors includes the starting or ending point in the rendered example while the after / before selectors excludes them.

The examples below use the same source file with different selection attributes.

To / from:

Code:
{% code-snippet
  file="./code-examples/useTabs.ts"
  from=12
  to=14
/%}
Result:
  const setTabRef = useCallback((element: HTMLButtonElement | null, index: number) => {
    tabRefs.current[index] = element;
  }, []);

After / before:

Code:
{% code-snippet
  file="./code-examples/useTabs.ts"
  after=12
  before=14
/%}
Result:
    tabRefs.current[index] = element;

Add file names to code snippets

Add a file name to display in the code snippet header using the title attribute:

```js {% title="scripts.js" %}
function test() {
  console.log('Hello World!');
}
```

Result:

scripts.js
function test() {
  console.log('Hello World!');
}

Shorten long code snippets

Display only the first lines of a long code snippet using the previewLines attribute. Readers select Show more to display the rest of the snippet. The copy button always copies the full snippet.

```yaml {% title="redocly.yaml" previewLines=3 %}
seo:
  title: Museum API
navbar:
  items:
    - page: index.md
      label: Home
footer:
  copyrightText: Copyright © Museum
```

Result:

redocly.yaml
seo:
  title: Museum API
navbar:

The attribute works the same way on the code-snippet tag:

{% code-snippet file="./redocly.yaml" previewLines=3 /%}

To use the same number of lines for every code snippet, set previewLines in redocly.yaml.

Highlight lines and text

Highlight a specific line using [!code highlight]:

```js
function test() {
  console.log('Hello World!'); // [!code highlight]
}
```

Result:

function test() {
  console.log('Hello World!');
}

Highlight multiple consecutive lines:

```js 
// [!code highlight:3]
function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);
}
```

Result:

function test() { 
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);
}

Highlight non-consecutive lines using the highlight attribute:

```js {% highlight="{1,3-4}" %}
function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);
}
```

Result:

function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);
}

Highlight specific words or symbols:

```js
// [!code word:Hello]
function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);  // prints "Hello World"
}
```

Result:

function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);  // prints "Hello World"
}

Focus on specific lines by dimming others with a code comment:

```js
function test() {
  const hello = 'Hello'; // [!code focus]
  const world = 'World';
  console.log(hello + " " + world);
}
```

Or with a Markdoc tag and a pattern.

```js {% highlight="/Hello/" %}
function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);  // prints "Hello World"
}
```

Result:

function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);
}

Mark lines with error and warning levels:

```js
function test() {
  console.log('No errors or warnings');
  console.error('Error'); // [!code error]
  console.warn('Warning'); // [!code warning]
}
```

Result:

function test() {
  console.log('No errors or warnings');
  console.error('Error');
  console.warn('Warning');
}

Show added and removed lines:

```js
function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world); // [!code --]
  console.log(`${hello} ${world}`); // [!code ++]
}
```

Result:

function test() {
  const hello = 'Hello';
  const world = 'World';
  console.log(hello + " " + world);
  console.log(`${hello} ${world}`);
}

Best practices

Minimize complexity

Avoid unnecessary details or context. Simplified code snippets are easier for your readers to understand and apply.

Centralize example files

Store your example code in a central directory to make them easier to manage, update, and reference from code snippet tags.

Resources