| 1 |
--- |
| 2 |
title: transform.HighlightCodeBlock |
| 3 |
description: Returns highlighted code received in context within a code block render hook. |
| 4 |
categories: [] |
| 5 |
keywords: [highlight] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [] |
| 9 |
returnType: highlight.HighlightResult |
| 10 |
signatures: ['transform.HighlightCodeBlock CONTEXT [OPTIONS]'] |
| 11 |
--- |
| 12 |
|
| 13 |
The `transform.HighlightCodeBlock` function uses the [`alecthomas/chroma`][] package to generate syntax-highlighted HTML from code received in context within a code block render hook. This function is only useful within a code block render hook. |
| 14 |
|
| 15 |
## Arguments |
| 16 |
|
| 17 |
CONTEXT |
| 18 |
: The [context][] passed into a code block render hook. |
| 19 |
|
| 20 |
OPTIONS |
| 21 |
: (`map`) A map of key-value pairs. See the [options](#options-1) below. The key names are case-insensitive. |
| 22 |
|
| 23 |
## Return value |
| 24 |
|
| 25 |
`transform.HighlightCodeBlock` returns a `HighlightResult` object with two methods. |
| 26 |
|
| 27 |
`Wrapped` |
| 28 |
: (`template.HTML`) Returns highlighted code wrapped in `<div>`, `<pre>`, and `<code>` elements. This is identical to the value returned by the `transform.Highlight` function. |
| 29 |
|
| 30 |
`Inner` |
| 31 |
: (`template.HTML`) Returns highlighted code without any wrapping elements, allowing you to create your own wrapper. |
| 32 |
|
| 33 |
## Examples |
| 34 |
|
| 35 |
```go-html-template |
| 36 |
{{ $result := transform.HighlightCodeBlock . }} |
| 37 |
{{ $result.Wrapped }} |
| 38 |
``` |
| 39 |
|
| 40 |
To override the default options: |
| 41 |
|
| 42 |
```go-html-template |
| 43 |
{{ $opts := merge .Options (dict "lineNos" true) }} |
| 44 |
{{ $result := transform.HighlightCodeBlock . $opts }} |
| 45 |
{{ $result.Wrapped }} |
| 46 |
``` |
| 47 |
|
| 48 |
To fall back to plain text when the language is not supported by the highlighter: |
| 49 |
|
| 50 |
```go-html-template |
| 51 |
{{ $opts := dict }} |
| 52 |
{{ if not (transform.CanHighlight .Type) }} |
| 53 |
{{ $opts = dict "type" "text" }} |
| 54 |
{{ end }} |
| 55 |
{{ $result := transform.HighlightCodeBlock . $opts }} |
| 56 |
{{ $result.Wrapped }} |
| 57 |
``` |
| 58 |
|
| 59 |
## Options |
| 60 |
|
| 61 |
The `transform.HighlightCodeBlock` function accepts an options map. |
| 62 |
|
| 63 |
{{% include "_common/syntax-highlighting-options.md" %}} |
| 64 |
|
| 65 |
`code` |
| 66 |
: {{< new-in 0.162.0 />}} |
| 67 |
: (`string`) Overrides the code received from the code block context. |
| 68 |
|
| 69 |
`type` |
| 70 |
: {{< new-in 0.162.0 />}} |
| 71 |
: (`string`) Overrides the language received from the code block context. |
| 72 |
|
| 73 |
[`alecthomas/chroma`]: https://github.com/alecthomas/chroma |
| 74 |
[context]: /render-hooks/code-blocks/#context |