博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Node.js] Provide req.locals data though middleware
阅读量:7123 次
发布时间:2019-06-28

本文共 1784 字,大约阅读时间需要 5 分钟。

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 onconst 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 dataexports.dump = (obj) => JSON.stringify(obj, null, 2);// Making a static map is really long - this is a handy helper function to make oneexports.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 SVGexports.icon = (name) => fs.readFileSync(`./public/images/icons/${name}.svg`);// Some details about the siteexports.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 requestsapp.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 layoutblock content    h2 Sale ends in #{hlp.moment().endOf('day').fromNow()}

 

转载地址:http://ygxel.baihongyu.com/

你可能感兴趣的文章
长长的望远镜
查看>>
在给予react的ANTD中如何改变某些固定项?
查看>>
慕课网_《使用Google Guice实现依赖注入》学习总结
查看>>
Calendar工具类对跨年的星期的处理个人总结
查看>>
云计算和DevOps那点事
查看>>
什么是客户端负载均衡
查看>>
【mongoDB查询进阶】聚合管道(二) -- 阶段操作符
查看>>
2017-07-15 前端日报
查看>>
Android布局优化:ViewStub标签实现延迟加载(源码解析原理)
查看>>
Webpack快速入门
查看>>
HandlerThread与AsyncQueryHandler源码分析
查看>>
caffe原理之softmax函数
查看>>
数据分组统计
查看>>
记录fastclick中一次手动触发click事件失败
查看>>
云框架发布KONG API Gateway主题,开源求助攻~
查看>>
从一次报错聊聊 Point 事件
查看>>
JS attribute and prpperty
查看>>
SpringMVC配置太多?试试SpringBoot
查看>>
详解js深浅复制
查看>>
Laravel 服务容器实现原理
查看>>