【问题标题】:Using Handlebars with Deno v1.6.x在 Deno v1.6.x 中使用 Handlebars
【发布时间】:2020-12-29 21:49:28
【问题描述】:

我正在努力让 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 的经验?

干杯。

【问题讨论】:

    标签: javascript handlebars.js deno oak


    【解决方案1】:

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

    如果您不想要默认布局文件,则可以这样做:

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

    这是 renderView 的 code

      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 的文件(前提是您使用的是默认配置)。

    您还可以传递一个布局参数以在布局文件中呈现它,该文件位于您的布局目录中。

    【讨论】:

    • 谢谢,但我认为这就是我的代码正在做的事情。我正在传递main 的布局参数,并且把手文件位于默认的views/ 目录中。你能解释一下我错了哪条路,因为我很难看到它。我已经在顶部包含了项目结构。
    • @MarkTyers 您将视图参数作为主参数传递,而不是布局参数。阅读代码。将您的主文件上移一级到视图目录中,它将起作用
    • 那是我最初放置的地方,但它不起作用。
    • @MarkTyers 你在使用默认配置吗?
    • 是的,我在原始帖子中发布了我正在运行的脚本。干杯。
    猜你喜欢
    • 2012-08-07
    • 2021-03-06
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2020-09-16
    • 2020-09-13
    • 1970-01-01
    • 2022-12-24
    相关资源
    最近更新 更多