mirror of
https://github.com/LucasVbr/hono-pug-renderer.git
synced 2026-05-13 17:21:51 +00:00
feat(#5): Use c.render() method instead of c.pug()
This commit is contained in:
@@ -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!'
|
||||||
});
|
});
|
||||||
|
|||||||
+22
-11
@@ -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 };
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user