在Deno v1.6.x中使用Handlebars



我正在努力让Handlebars模板与Deno v1.6.x一起工作,有什么想法吗?

$ deno --version
deno 1.6.2 (release, x86_64-unknown-linux-gnu)
v8 8.8.278.2
typescript 4.1.3
$ tree
.
├── template.js
└── views
├── layouts
│   └── main.hbs
└── partials
/* template.js */
import { Application, Router, Status } from 'https://deno.land/x/oak/mod.ts'
import { Handlebars } from 'https://deno.land/x/handlebars/mod.ts'
const port = 8080
const app = new Application()
const router = new Router()
const handle = new Handlebars()
// error handler
app.use(async (context, next) => {
try {
await next()
} catch (err) {
console.log(err)
}
})
// the routes defined here
router.get('/', async context => {
const data = {
title: 'Fools Day',
date: '01/04/20'
}
context.response.body = await handle.renderView('main', data)
})
app.use(router.routes())
app.use(router.allowedMethods())
// static content
app.use(async (context, next) => {
const root = `${Deno.cwd()}/static`
try {
await context.send({ root })
} catch {
next()
}
})
// page not found
app.use( async context => {
context.response.status = Status.NotFound
context.response.body = `"${context.request.url}" not found`
})
app.addEventListener("listen", ({ port }) => console.log(`listening on port: ${port}`) )
await app.listen({ port })

当我尝试查看页面时,我得到以下错误:

$ deno run --allow-net --unstable template.js
Check file:///home/xxx/template.js
listening on port: 8080
NotFound: No such file or directory (os error 2)
at processResponse (deno:core/core.js:223:11)
at Object.jsonOpAsync (deno:core/core.js:240:12)
at async open (deno:runtime/js/30_files.js:44:17)
at async readFile (deno:runtime/js/40_read_file.js:15:18)
at async Handlebars.render (mod.ts:98:53)
at async Handlebars.renderView (mod.ts:76:26)
at async file:///home/xxx/template.js:28:26
at async dispatch (middleware.ts:41:7)
at async dispatch (middleware.ts:41:7)
at async dispatch (middleware.ts:41:7)

我在https://deno.land/x/handlebars@v0.6.0,我认为我已经使用了所有默认设置,但错误消息并没有告诉我找不到什么文件。

有人和Deno一起使用Handlebars吗?

干杯。

编辑:确保您有一个符合默认布局的布局文件!!

如果你不想要一个默认的布局文件,那么你可以这样做:

const handle = new Handlebars({defaultLayout:''});

以下是renderView 的代码

public async renderView(
view: string,
context?: Record<string, unknown>,
layout?: string,
): Promise<string> {
if (!view) {
console.warn("View is null");
return "";
}
const config: HandlebarsConfig = this.config as HandlebarsConfig;
const partialsPathes = await this.getTemplatesPath(
join(config.baseDir, config.partialsDir),
);
partialsPathes && (await this.registerPartials(partialsPathes));
const path = join(config.baseDir, view + config.extname);
const body: string = await this.render(path, context);
layout = (layout as string) || config.defaultLayout;
if (layout) {
const layoutPath: string = join(
config.baseDir,
config.layoutsDir,
layout + config.extname,
);
return this.render(layoutPath, { ...context, body });
}
return body;
}

第一个参数,在您的案例中是main,它告诉代码在views目录中查找名为main.hbs的文件(前提是使用默认配置(。

您还可以传递布局参数,以便在布局目录中的布局文件中渲染它。

相关内容

  • 没有找到相关文章

最新更新