`Nunjucks模板引擎基本语法

- Nunjucks:用于模板渲染,支持变量、条件和循环语法。  

- URL模块:用于处理文件路径和URL转换,`import.meta.url`获取当前模块路径,`new URL()`解析路径,`fileURLToPath()`转换为本地路径。

## Nunjucks模板引擎

### 1. 基本语法

- **变量**:`{{ 变量名 }}`  

- **条件语句**:  

  ```nunjucks

  {% if 条件 %}

      内容

  {% else %}

      内容

  {% endif %}

  ```  

  示例:

  ```nunjucks

  {% if user %}

     

用户已登录:{{ user.name }}

  {% else %}

     

用户未登录

  {% endif %}

  ```

- **循环语句**:  

  ```nunjucks

  {% for item in 数组 %}

      内容

  {% endfor %}

  ```  

  示例:

  ```nunjucks

 

          {% for item in items %}

             

  • {{ item }}
  •       {% endfor %}

     

  ```

### 2\. 在Node.js中配置Nunjucks

```javascript

import Nunjucks from 'nunjucks';

import { fileURLToPath } from 'url';

export const setupNunjucks = () => {

    const templatePath = new URL('../Views', import.meta.url);

    const path = fileURLToPath(templatePath);

    Nunjucks.configure(path);

};

```


 

## 二、Node.js URL模块

### 1. `import.meta.url`

- 用途:获取当前模块的完整URL(以`file://`开头)。  

- 示例:

  ```javascript

  console.log(import.meta.url); // 输出:file:///path/to/module.js

  ```

### 2. `new URL()`

- 用途:从基准URL解析相对路径。  

- 示例:

  ```javascript

  const base = new URL('file:///path/to/module.js');

  const relative = '../views';

  const result = new URL(relative, base);

  console.log(result.href); // 输出:file:///path/views

  ```

### 3\. `fileURLToPath()`

- 用途:将`file://`协议的URL转换为本地文件路径。  

- 示例:

  ```javascript

  import { fileURLToPath } from 'url';

  const url = new URL('file:///path/views');

  const path = fileURLToPath(url);

  console.log(path); // 输出:/path/views

  ```






 

你可能感兴趣的:(vim,编辑器,linux)