Hiding source code in an Eleventy post
The trick is that the shortcode must return the blank lines around the content so the Markdown processor (running after Nunjucks) treats the code fence as a block rather than literal text inside an HTML element.
This is the desired result. The blanks lines surrounding the code fences are very important.
<details class="code-display">
<summary>Creating a FlexSearch document index</summary>
<div>
```
index = new Document({
document: {
id: "id",
store: ["id", "title", "url", "tags", "folder", "description"],
//store: true,
index: ["title", "url", "content", "tags", "description"],
tag: "folder",
},
tokenize: "forward",
});
```
</div>
</details>
In .eleventy.js:
eleventyConfig.addPairedShortcode("codeDetails", function(content, title) {
return `<details class="code-display">\n<summary>${title}</summary>\n<div>\n\n${content}\n\n</div>\n</details>`;
});
Then in any .md file:
```
{% codeDetails "Creating a FlexSearch document index" %}
```js
index = new Document({
document: {
id: "id",
...
}
});
```
{% endcodeDetails %}
```
```
Why the blank lines matter: When the Markdown parser sees the output, <details> opens an HTML block — but a blank line ends that HTML block, allowing the ``` fence to be processed as a Markdown code block. Without the blank lines in the returned string, the fence would render as literal backticks.
Processing order that makes this work:
- Nunjucks runs → shortcode receives the raw
```js ... ```string, wraps it with the HTML + blank lines - Markdown runs → blank lines let the code fence be parsed as Markdown inside the HTML structure
This is exactly why your current hand-written version requires the blank lines inside the <div>.... ``` ` string, wraps it with the HTML + blank lines
2. Markdown runs → blank lines let the code fence be parsed as Markdown inside the HTML structure
This is exactly why your current hand-written version requires the blank lines inside the <div>.