Markdown代码块的基础和高级语法

Published on
Published on
/3 mins read/---

基础语法

使用三个反引号在markdown中创建代码块

```language
你的代码写在这里
```

示例

```js
function debounce(func, timeout = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}
```

将显示为:

function debounce(func, timeout = 300) {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, timeout)
  }
}

文件名

language 后添加 :filename.ext 可以在代码块顶部显示文件名标签

示例:

```java:GetRowValue.java
private String[] getRowValue(Integer i, List<BillDetail> billDetail) {
  String[] rowValue = new String[5];
  rowValue[0] = (i).toString();
  i = i - 1;

  rowValue[1] = billDetail.get(i).getTenSanPham();
  rowValue[2] = billDetail.get(i).getSoLuong().toString();
  rowValue[3] = new DecimalFormat("#,###").format(Integer.parseInt(billDetail.get(i).getDonGiaSanPham()));
  rowValue[4] = new DecimalFormat("#,###").format(billDetail.get(i).getThanhTien());
  return rowValue;
}
```

将显示为:

GetRowValue.java
private String[] getRowValue(Integer i, List<BillDetail> billDetail) {
  String[] rowValue = new String[5];
  rowValue[0] = (i).toString();
  i = i - 1;
 
  rowValue[1] = billDetail.get(i).getProductName();
  rowValue[2] = billDetail.get(i).getQuantity().toString();
  rowValue[3] = new DecimalFormat("#,###").format(Integer.parseInt(billDetail.get(i).getProductPrice()));
  rowValue[4] = new DecimalFormat("#,###").format(billDetail.get(i).getSubTotal());
 
  return rowValue;
}

行高亮和行号

  • language 后添加 {numbers} 属性来高亮指定行
  • language 后添加 showLineNumbers 属性来显示行号

示例:

```html:index.html {1,4-6,10} showLineNumbers
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello world</title>
  </head>
  <body>
    <h1>Hello world</h1>
  </body>
</html>
```

将显示为:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Hello world</title>
  </head>
  <body>
    <h1>Hello world</h1>
  </body>
</html>

高级技巧

行高亮语法说明

  • {1} - 高亮第1行
  • {1,3,5} - 高亮第1、3、5行
  • {1-5} - 高亮第1到5行
  • {1,3-5,8} - 高亮第1行、第3到5行、第8行

常用语言标识符

  • JavaScript: js, javascript
  • TypeScript: ts, typescript
  • Python: py, python
  • Java: java
  • C++: cpp, c++
  • HTML: html
  • CSS: css
  • JSON: json
  • Bash: bash, sh
  • SQL: sql

内联代码

对于单行代码或代码片段,使用单个反引号:

使用 `console.log()` 来输出调试信息。

将显示为:使用 console.log() 来输出调试信息。