Components
Code block
Display blocks of code for documentation purposes.
Contents
Important information
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.
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) => {
if(n < 0) {
throw 'Fibonacci not defined for negative numbers';
}
if(n < 2) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}</code></pre>
</div>
Nunjucks
Nunjucks options
| Name | Type | Description |
|---|---|---|
| filename | string |
The filename to display in the code block's title bar. Default value: |
| 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 Default value: |
| 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
{% 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"
}) }}
Component status
- Phase
- To be reviewed
- Tested without JavaScript
- Yes
- Tested without CSS
- Yes
- Passed DAC audit
- Not yet audied
- Documentation complete
- No
Syntax highlighting
Code blocks can be syntax highlighted with Prism.js.