Merge pull request #7 from LucasVbr/dev

Dev
This commit is contained in:
Lucàs
2025-05-29 09:11:32 +02:00
committed by GitHub
3 changed files with 27 additions and 16 deletions
+2 -2
View File
@@ -46,7 +46,7 @@ const app = new Hono();
app.use('*', pugRenderer(path.join(__dirname, 'views'))); app.use('*', pugRenderer(path.join(__dirname, 'views')));
app.get('/', (c) => { app.get('/', (c) => {
return c.pug('index'); return c.render('index');
}); });
export default app; export default app;
@@ -58,7 +58,7 @@ You can pass options to the `pugRenderer` function to customize its behavior.
```javascript ```javascript
app.get('/', (c) => { app.get('/', (c) => {
return c.pug('index', { return c.render('index', {
title: 'My Page', title: 'My Page',
message: 'Hello, world!' message: 'Hello, world!'
}); });
+1 -1
View File
@@ -4,7 +4,7 @@
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
"type": "module", "type": "module",
"version": "0.0.1", "version": "0.0.2",
"description": "Pug renderer middleware for Hono", "description": "Pug renderer middleware for Hono",
"scripts": { "scripts": {
"build": "bun build --target=node ./src/index.ts --outfile=./dist/index.js && bun run build:declaration", "build": "bun build --target=node ./src/index.ts --outfile=./dist/index.js && bun run build:declaration",
+22 -11
View File
@@ -1,23 +1,34 @@
import { Context } from 'hono'; import type {Context, MiddlewareHandler, Next} from 'hono';
import {renderFile} from 'pug'; import {renderFile} from 'pug';
import path from 'path'; import path from 'path';
declare module 'hono' { declare module 'hono' {
interface Context { interface ContextRenderer {
pug: (template: string, locals?: Record<string, any>) => Response; /**
* 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<Response>
*/
(
template: string,
locals?: Record<string, any>,
): Response | Promise<Response>;
} }
} }
function pugRenderer(viewsPath: string) { /**
return async (c: Context, next: () => Promise<void>) => { * Middleware to render Pug templates.
c.pug = (template: string, locals: Record<string, any> = {}) => { * @param viewPath - The directory where Pug templates are located.
const filePath = path.join(viewsPath, `${template}.pug`); */
export function pugRenderer(viewPath: string): MiddlewareHandler {
return async (c: Context, next: Next) => {
c.setRenderer((template: string, locals: Record<string, any> = {}) => {
const filePath = path.join(viewPath, `${template}.pug`);
const html = renderFile(filePath, locals); const html = renderFile(filePath, locals);
return c.html(html); return c.html(html);
}; });
await next(); await next();
}; };
} }
export { pugRenderer };