Mastering markdown code blocks - guide with examples and best practices | Extraparse

Mastering markdown code blocks - guide with examples and best practices

September 11, 20224 min read625 words

Table of Contents

Learn how to effectively use Markdown code blocks with our comprehensive guide. This article explores various examples, syntax highlighting, interactive elements, and best practices to enhance your Markdown documents. Whether you're a beginner or looking to refine your Markdown skills, this guide has something for you.

Introduction

Markdown is a lightweight markup language that allows you to format text using simple syntax. One of its powerful features is the ability to include code blocks that can display code snippets with proper formatting and syntax highlighting. This guide will walk you through various ways to utilize code blocks in Markdown effectively.

Basic Code Blocks

Creating a basic code block in Markdown is straightforward. Use triple backticks (```) followed by the language identifier for syntax highlighting.

Example

1(function () {
2 var cache = {};
3 var form = $("form");
4 var minified = true;
5
6 var dependencies = {};
7
8 var treeURL =
9 "https://api.github.com/repos/PrismJS/prism/git/trees/gh-pages?recursive=1";
10 var treePromise = new Promise(function (resolve) {
11 $u.xhr({
12 url: treeURL,
13 callback: function (xhr) {
14 if (xhr.status < 400) {
15 resolve(JSON.parse(xhr.responseText).tree);
16 }
17 },
18 });
19 });
20})();

Advanced Code Blocks

Advanced code blocks can include additional features like JSDoc comments, line highlighting, and line numbers to enhance readability and comprehension.

JSDoc Comment Example

1/**
2 * Get value out of string (e.g. rem => px)
3 * If value is px strip the px part
4 * If the input is already a number only return that value
5 * @param {string | number} input
6 * @param {number} [rootFontSize]
7 * @return {number} Number without last three characters
8 * @example removeLastThree('6rem') => 6
9 */
10const getValue = (input, rootFontSize = 16) => {
11 if (typeof input === `number`) {
12 return input / rootFontSize;
13 }
14
15 const isPxValue = input.slice(-2) === `px`;
16
17 if (isPxValue) {
18 return parseFloat(input.slice(0, -2));
19 }
20
21 return parseFloat(input.slice(0, -3));
22};
23
24// Helper function to add two numbers
25const helper = (a, b) => a + b;
26
27// Helper function to multiply two numbers with detailed computation
28const morehelper = (a, b) => a * b;
29
30export { getValue, helper, morehelper };

Code Block with Line Highlighting and Numbers

1import * as React from "react";
2
3const Post = ({ data: { post } }) => (
4 <Layout>
5 <Heading variant="h2" as="h2">
6 {post.title}
7 </Heading>
8 <p
9 sx={{
10 color: `secondary`,
11 mt: 3,
12 a: { color: `secondary` },
13 fontSize: [1, 1, 2],
14 }}
15 >
16 <span>{post.date}</span>
17 {post.tags && (
18 <React.Fragment>
19 {``}
20 <ItemTags tags={post.tags} />
21 </React.Fragment>
22 )}
23 </p>
24 <section
25 sx={{
26 ...CodeStyles,
27 my: 5,
28 ".gatsby-resp-image-wrapper": { my: 5, boxShadow: `lg` },
29 }}
30 >
31 <MDXRenderer>{post.body}</MDXRenderer>
32 </section>
33 </Layout>
34);
35
36export default Post;

Integrating React Components

Markdown allows embedding React components to create interactive and dynamic content within your documents.

Example with Spotify Player

Here will a React component go:

Best Practices

To ensure your Markdown code blocks are effective and maintainable, consider the following best practices:

  • Specify Language: Always specify the programming language after the opening backticks for proper syntax highlighting.

    1def hello_world():
    2 print("Hello, World!")
  • Add Comments: Include comments within your code snippets to explain complex logic or important sections.

  • Consistent Formatting: Maintain consistent indentation and formatting for better readability.

  • Use Meaningful Titles: When adding titles to code blocks, ensure they are descriptive and relevant.

Additional Resources

Conclusion

Mastering Markdown code blocks is essential for creating clear and professional documentation. By incorporating syntax highlighting, comments, and adhering to best practices, you can enhance the readability and functionality of your Markdown files. Start implementing these techniques in your projects and explore advanced features to take your Markdown skills to the next level. Happy coding!