Express框架中使用EJS模板引擎并结合silly-datetime库进行日期格式化的实现方法 原创

Thalia ·
更新时间:2024-09-20
· 428 次阅读

在 Express 框架中使用 EJS 模板引擎并结合 silly-datetime 库进行日期格式化的步骤如下:

1. 安装 silly-datetime 库

可以通过 npm 命令安装 silly-datetime 库,命令为:

npm install silly-datetime --save 2. 在 app.js 中配置模板引擎和使用库方法

在 app.js 文件中,需要配置使用 EJS 模板引擎,并使用 res.locals 将库方法传递给模板。下面是一个例子:

const express = require('express'); const app = express(); const sd = require('silly-datetime'); // 模板引擎配置 app.set('views', __dirname + '/views'); // 设置模板文件夹 app.set('view engine', 'ejs'); // 设置视图模板引擎 // 定义全局变量,模板都可以访问到 app.use(function (req, res, next) {   // 将 silly-datetime 的 format 方法用 locals 来代理   res.locals.formatDate = function (date, fmt) {     return sd.format(date, fmt);   };   next(); }); // 创建路由和功能代码 // ... 3. 在模板文件中使用库方法

在模板文件中,可以使用模板语法调用布局文件中定义的  formatDate 函数。具体方式如下:

<!-- 渲染数据列表 --> <% for(var i=0; i<articles.length; i++) { %>   <tr>     <td><%= articles[i].title %></td>     <td><%= locals.formatDate(articles[i].created_at, 'YYYY-MM-DD HH:mm:ss') %></td>   </tr> <% } %>

以上模板代码将使用 silly-datetime 的 format 方法对文章发布时间进行了格式化处理,最终展示为 YYYY-MM-DD HH:mm:ss 格式的日期字符串。

注意:在模板文件中需要正确引入 silly-datetime 库,否则无法使用 formatDate 函数。

补充说明:silly-datetime 库的原始用法为:

const sd = require('silly-datetime'); sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');//此处的new Date()位置可以传入其他日期格式参数

对应的,在app.js中定义该函数给EJS模版使用,则对应形式为:

  res.locals.formatDate = function (date, fmt) {     return sd.format(date, fmt);   };

相应的,EJS模版中使用该函数,则是需要通过locals来调用定义的formatDate方法,再传入对应位置的参数即可:

locals.formatDate(articles[i].created_at, 'YYYY-MM-DD HH:mm:ss')

该方法经笔者测试可以正常使用。



express DateTime 方法 ejs 原创 格式化

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章