Skip to main content Skip to list of components
Service phase: Beta

This is a new service – give us your feedback to help improve it.

Components

Code block

Display blocks of code for documentation purposes.

Contents

  1. Component status
  2. Syntax highlighting

Important information

When displaying code, ensure that it is properly escaped to avoid potential security vulnerabilities.

Both Nunjucks and Jinja have the ability to autoescape template content and both enable the option by default. See Autoescaping in Nunjucks and Autoescaping in Jinja.

Open this example in new tab

HTML

<div class="tna-code-block" title="fibonacci.js">
  <button class="tna-button tna-code-block__copy tna-button--small tna-button--plain" type="button" hidden aria-live="assertive">
    Copy code
  </button>
  <pre class="tna-code-block__pre"><code class="language-javascript">const fibonacci = (n = 0) =&gt; {
    if(n &lt; 0) {
      throw &#39;Fibonacci not defined for negative numbers&#39;;
    }
    if(n &lt; 2) {
      return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}</code></pre>
</div>

Nunjucks

Nunjucks options
Primary options
Name Type Description
filename string

The filename to display in the code block's title bar.

Default value: plain

code string

Required.

The code content to display in the code block.

language string

If set, adds the programming language of the code block which enables syntax highlighting with Prism.js.

copy boolean

If true, show a copy button in the code block.

Default value: false

classes string

Classes to add to the code block element.

attributes object

HTML attributes (for example data attributes) to add to the code block element.

{% from "nationalarchives/components/code-block/macro.njk" import tnaCodeBlock %}

{{ tnaCodeBlock({
  language: "javascript",
  code: "const fibonacci = (n = 0) => {
    if(n < 0) {
      throw 'Fibonacci not defined for negative numbers';
    }
    if(n < 2) {
      return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}",
  filename: "fibonacci.js"
}) }}

Jinja

Important information

This is an experimental feature that outputs a Jinja template based on the Nunjucks example. Check the converted code for accuracy.
{% from "components/code-block/macro.html" import tnaCodeBlock %}

{{ tnaCodeBlock({
  "language": "javascript",
  "code": "const fibonacci = (n = 0) => {
    if(n < 0) {
      throw 'Fibonacci not defined for negative numbers';
    }
    if(n < 2) {
      return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}",
  "filename": "fibonacci.js"
}) }}
Phase
To be reviewed
Tested without JavaScript
Yes
Tested without CSS
Yes
Passed DAC audit
Not yet audied
Documentation complete
No

Code blocks can be syntax highlighted with Prism.js.


Back to top