[Node.js] Provide req.locals data though middleware
2023-09-14 09:00:51 时间
We can create Template Helpers, which can contains some common reuseable data and libs.
/* This is a file of data and helper functions that we can expose and use in our templating function */ // FS is a built in module to node that let's us read files from the system we're running on const fs = require('fs'); // moment.js is a handy library for displaying dates. We need this in our templates to display things like "Posted 5 minutes ago" exports.moment = require('moment'); // Dump is a handy debugging function we can use to sort of "console.log" our data exports.dump = (obj) => JSON.stringify(obj, null, 2); // Making a static map is really long - this is a handy helper function to make one exports.staticMap = ([lng, lat]) => `https://maps.googleapis.com/maps/api/staticmap?center=${lat},${lng}&zoom=14&size=800x150&key=${process.env.MAP_KEY}&markers=${lat},${lng}&scale=2`; // inserting an SVG exports.icon = (name) => fs.readFileSync(`./public/images/icons/${name}.svg`); // Some details about the site exports.siteName = `Now That's Delicious!`; exports.menu = [ { slug: '/stores', title: 'Stores', icon: 'store', }, { slug: '/tags', title: 'Tags', icon: 'tag', }, { slug: '/top', title: 'Top', icon: 'top', }, { slug: '/add', title: 'Add', icon: 'add', }, { slug: '/map', title: 'Map', icon: 'map', }, ];
Then you can define a locals data in middleware:
Require helper file:
const helpers = require('./helpers');
// pass variables to our templates + all requests app.use((req, res, next) => { res.locals.hlp = helpers; res.locals.flashes = req.flash(); res.locals.user = req.user || null; res.locals.currentPath = req.path; next(); });
Then in the pug file, you can use those locals variable:
extends layout
block content
h2 Sale ends in #{hlp.moment().endOf('day').fromNow()}
相关文章
- Clipboard.js_js复制文本代码
- 一步步带你实现web全景看房——three.js
- 开箱即用!Node.js+Mysql模块封装
- 原生 JS 实现 HTML 转 Markdown ,html2md.js
- 如何使用jscythe并通过Node.js的Inspector机制执行任意JS代码
- 【Node.js】寒露过三朝,聊聊zlib压缩
- JS拖拽元素 兼容IE详解编程语言
- 使用Node.js连接MySQL数据库(node-mysql)
- js 异步请求后各种监听事件的处理,如异步请求后click 事件失效详解编程语言
- 快速在Linux平台上安装Node.js(node安装linux)
- Node.js与MongoDB:联手打造高效应用(node与mongodb)
- Discovering the Power of Node.js on Linux: An Introduction(nodejslinux)
- 使用Node.js实现对MSSQL数据库的连接(node连接 mssql)
- 利用Node.js封装MSSQL的尝试(node mssql封装)
- 在js中单选框和复选框获取值的方式
- js父窗口控制子窗口的行为-打开,关闭,重定位,回复
- 兼容性非常好的js右下角与漂浮广告代码
- JavaScript(JS)压缩/混淆/格式化批处理工具
- JS实现下拉框的动态添加(附效果)
- js获取url参数代码实例分享(JS操作URL)
- 跟我学Nodejs(三)---Node.js模块
- Node.js中的模块机制学习笔记
- 使用js获取图片原始尺寸
- node.js中实现同步操作的3种实现方法
- node.js中的path.extname方法使用说明
- node.js中的buffer.length方法使用说明
- node.js中的fs.rename方法使用说明
- node.js中的fs.fchmod方法使用说明
- node.js中的fs.open方法使用说明
- node.js中的fs.createReadStream方法使用说明
- 使用VS开发Node.js指南
- Node.js服务器端应用开发框架--Hapi.js
- 使用node.js半年来总结的10条经验