2024-5-5

Code blocks in This Blog’s Markdown

A guide to using code blocks in this blog’s markdown

Table of Contents

Inline code

This is an inline code block.

Code blocks

markdown
```
import numpy as np
import matplotlib.pyplot as plt
```
Output:
import numpy as np
import matplotlib.pyplot as plt
markdown
```python[title=code.py]
import numpy as np
import matplotlib.pyplot as plt
```
Output:
code.py
import numpy as np
import matplotlib.pyplot as plt
markdown
```python[title=code.py,showLineNumbers=true]
import numpy as np
import matplotlib.pyplot as plt
```
Output:
code.py
1import numpy as np
2import matplotlib.pyplot as plt
Important
No spaces are allowed after commas in the code attributes.
✅ [title=asdf.py,showLineNumbers=true]
❌ [title=asdf.py, showLineNumbers=true]
code.js
1function createStyleObject(classNames, style) {
2  return classNames.reduce((styleObject, className) => {
3    return {...styleObject, ...style[className]};
4  }, {});
5}
6
7function createClassNameString(classNames) {
8  return classNames.join(' ');
9}
10
11
12function createChildren(style, useInlineStyles) {
13  let childrenCount = 0;
14  return children => {
15    childrenCount += 1;
16    return children.map((child, i) => createElement({
17      node: child,
18      style,
19      useInlineStyles,
20      key:`code-segment-${childrenCount}-${i}`
21    }));
22  }
23}
24
25function createElement({ node, style, useInlineStyles, key }) {
26  const { properties, type, tagName, value } = node;
27  if (type === "text") {
28    return value;
29  } else if (tagName) {
30    const TagName = tagName;
31    const childrenCreator = createChildren(style, useInlineStyles);
32    const props = (
33      useInlineStyles
34      ? { style: createStyleObject(properties.className, style) }
35      : { className: createClassNameString(properties.className) }
36    );
37    const children = childrenCreator(node.children);
38    return <TagName key={key} {...props}>{children}</TagName>;
39  }
40}