我正在尝试从我的Koa2中间件中获取var值,以显示在我的pug模板(或其他模板)中。例如,在koa-session中,我有:
app.use(ctx => {
// ignore favicon
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n; // how can I use this?
ctx.body = n + ' views'; // works, but in body directly
ctx.state.views = n + ' views'; // not working
});另一个例子是响应时间:
app.use(async (ctx, next) => {
const start = Date.now();
ctx.state.start = start
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); // this shows response
ctx.state.ms = await ms>0 // I have no idea what I'm doing :)
});按照最初的指令,这是可行的,但我想使用它作为模板变量,而不是使用body/console,因此在我的路由器/控制器中,我将具有:
...
return ctx.render("posts/index", {
title: 'Posts',
posts: posts,
ms: ctx.state.ms,
views: ctx.session.views // or views: ctx.state.views
});这些都不管用。它是否与async/await有关,因此它不能及时获得值,或者是一些语法问题?因为我是新手,所以请温文点。:)
发布于 2017-09-27 23:07:50
您需要在“会话”中间件中调用next(),方法与“响应时间”示例中的方法相同。
就像这样:
app.use((ctx, next) => {
let n = ctx.session.views || 0;
ctx.session.views = ++n;
next();
});
app.use(ctx => {
ctx.body = 'Hello ' + ctx.session.views;
// or you can return rendering result here
});有关更多信息,请查看其文档的Cascading部分
https://stackoverflow.com/questions/46444577
复制相似问题