Skip to content

Commit

Permalink
Do nunjucks code highlighting using nunjucks
Browse files Browse the repository at this point in the history
  • Loading branch information
frankieroberto committed Dec 6, 2023
1 parent 619c722 commit cd5d7ed
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
6 changes: 5 additions & 1 deletion docs/components/_example.njk
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
{% macro example(params) %}

{%- set nunjucksHtml -%}
<pre style="overflow: auto; background-color: #f3f2f1; padding: 10px 0;"><code>{{ getNunjucksCode(params.component) }}</code></pre>{% endset %}

```js
{{ getNunjucksCode(params.component) }}
```
{% endset %}

{%- set outputHtml %}<iframe style="width: 100%; display: block; max-width: 100%; border: 0; background: white; height: 300px;" src="/examples/{{ params.component }}"></iframe><p class="govuk-body-s" style="border-top: 1px solid #b1b4b6; padding: 10px 20px;"><a href="/examples/{{ params.component }}" class="govuk-link" target="_blank">Open this example in a new tab</a></p>{%- endset %}

Expand Down
11 changes: 4 additions & 7 deletions docs/eleventy.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
const govukEleventyPlugin = require('@x-govuk/govuk-eleventy-plugin')
const fs = require('fs')
const matter = require('gray-matter')
const hljs = require('highlight.js/lib/core');
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));

module.exports = function(eleventyConfig) {
// Register the plugin
Expand Down Expand Up @@ -42,13 +40,12 @@ module.exports = function(eleventyConfig) {
})

eleventyConfig.addNunjucksGlobal("getNunjucksCode", function(componentName) {
let data = matter(fs.readFileSync(`examples/${componentName}.njk`, 'utf-8')).content
let nunjucksCode = matter(fs.readFileSync(`examples/${componentName}.njk`, 'utf-8')).content

data = data.replace(/\{\%\sfrom\s[^\n]+\n\n/, '')
// Remove the `{% from "..." import ... %}` lines as those aren’t needed by users.
nunjucksCode = nunjucksCode.replace(/\{\%\sfrom\s[^\n]+\n\n/, '')

const highlightedCode = hljs.highlight(data, { language: 'js' }).value

return highlightedCode;
return nunjucksCode;
})

// Passthrough
Expand Down

0 comments on commit cd5d7ed

Please sign in to comment.