[Node.js] Provide req.locals data though middleware

來源:互聯網
上載者:User

標籤:node.js   library   tags   als   ges   adf   sys   local   common   

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()}

 

[Node.js] Provide req.locals data though middleware

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.