Skip to main content
Deno 2 is finally here 🎉️
Learn more
Deno Handlebars.js

Deno Handlebars Renderer

This is a Deno module that provides a simple and convenient way to render Handlebars templates.

Installation

To use this module, you can import it directly from the Deno module registry:

import { render } from "https://deno.land/x/deno_hbs/mod.ts";

Usage

Importing the module

First, import the render function from the module:

import { render } from "https://deno.land/x/deno_hbs/mod.ts";

Default Configuration

The module includes a default Handlebars configuration that you can use without providing any custom configuration. Here’s the default configuration:

DEFAULT_HANDLEBARS_CONFIG = {
  baseDir: "views",
  extname: ".hbs",
  layoutsDir: "layouts/",
  partialsDir: "partials/",
  cachePartials: true,
  defaultLayout: "main",
  helpers: undefined,
  compilerOptions: undefined,
};

Rendering a Handlebars Template

To render a Handlebars template, call the render function and provide the necessary parameters:

const template = `
    Hello, {{ name }}!
`;

const variables = {
  name: "John",
};

const renderedTemplate = await render({
  view: template,
  variables,
});

You can customize the rendering behavior by providing optional configuration parameters:

  • config: A Handlebars configuration object (optional).
  • baseDir: Base directory for template files (default: “views”).
  • extname: File extension for template files (default: “.hbs”).
  • layoutsDir: Directory for layout templates (default: “layouts/”).
  • partialsDir: Directory for partial templates (default: “partials/”).
  • cachePartials: Cache partial templates (default: true).
  • defaultLayout: Default layout template (default: “main”).
const renderedTemplate = await render({
  view: template,
  variables,
  baseDir: "templates",
  extname: ".handlebars",
  layoutsDir: "layouts/",
  partialsDir: "partials/",
  cachePartials: false,
  defaultLayout: "default",
});

Using with Oak Framework

Here’s an example of how you can use the module with the Oak framework:

import { Application, Router } from "https://deno.land/x/oak@v12.1.0/mod.ts";

const app = new Application();

const router = new Router();

const Home = async ({ response }: { response: any }) => {
  response.body = await hbs.render({
    view: 'home',
    variables: {
      data: "Your data here",
    },
    defaultLayout: "main"
  });
}

app.use(router.routes());
app.use(router.allowedMethods());

console.log('Server running on port : 3000!')
await app.listen({ port: 3000 });

License

This Deno module is licensed under the MIT License.

Acknowledgements

This module utilizes the Handlebars templating engine.

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please feel free to create a pull request.

Support

If you need help or have any questions, you can reach out to the maintainers or open an issue in the GitHub repository.