diff --git a/README.md b/README.md index 466f379..2c73137 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ const app = new Hono(); app.use('*', pugRenderer(path.join(__dirname, 'views'))); app.get('/', (c) => { - return c.pug('index'); + return c.render('index'); }); export default app; @@ -58,7 +58,7 @@ You can pass options to the `pugRenderer` function to customize its behavior. ```javascript app.get('/', (c) => { - return c.pug('index', { + return c.render('index', { title: 'My Page', message: 'Hello, world!' }); diff --git a/package.json b/package.json index d62ac3d..28d14cc 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "main": "dist/index.js", "types": "dist/index.d.ts", "type": "module", - "version": "0.0.1", + "version": "0.0.2", "description": "Pug renderer middleware for Hono", "scripts": { "build": "bun build --target=node ./src/index.ts --outfile=./dist/index.js && bun run build:declaration", diff --git a/src/index.ts b/src/index.ts index 447443e..ae8449d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,23 +1,34 @@ -import { Context } from 'hono'; -import { renderFile } from 'pug'; +import type {Context, MiddlewareHandler, Next} from 'hono'; +import {renderFile} from 'pug'; import path from 'path'; declare module 'hono' { - interface Context { - pug: (template: string, locals?: Record) => Response; + interface ContextRenderer { + /** + * Renders a template with optional local variables. + * + * @param template - The name of the template to render. + * @param locals - Optional key-value pairs to pass to the template. + * @returns A Response or Promise + */ + ( + template: string, + locals?: Record, + ): Response | Promise; } } -function pugRenderer(viewsPath: string) { - return async (c: Context, next: () => Promise) => { - c.pug = (template: string, locals: Record = {}) => { - const filePath = path.join(viewsPath, `${template}.pug`); +/** + * Middleware to render Pug templates. + * @param viewPath - The directory where Pug templates are located. + */ +export function pugRenderer(viewPath: string): MiddlewareHandler { + return async (c: Context, next: Next) => { + c.setRenderer((template: string, locals: Record = {}) => { + const filePath = path.join(viewPath, `${template}.pug`); const html = renderFile(filePath, locals); return c.html(html); - }; + }); await next(); }; -} - -export { pugRenderer }; - +} \ No newline at end of file