From 2c93cfba79b91299c08c5abb34892527a2097aa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luc=C3=A0s?= <86352901+LucasVbr@users.noreply.github.com> Date: Sat, 24 May 2025 12:43:11 +0200 Subject: [PATCH] feat(#5): Use c.render() method instead of c.pug() --- README.md | 4 ++-- src/index.ts | 37 ++++++++++++++++++++++++------------- 2 files changed, 26 insertions(+), 15 deletions(-) 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/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