mirror of
https://github.com/LucasVbr/hono-pug-renderer.git
synced 2026-05-13 17:21:51 +00:00
Merge pull request #6 from LucasVbr/feat/5-use-render
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.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!'
|
||||
});
|
||||
|
||||
+24
-13
@@ -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<string, any>) => 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<Response>
|
||||
*/
|
||||
(
|
||||
template: string,
|
||||
locals?: Record<string, any>,
|
||||
): Response | Promise<Response>;
|
||||
}
|
||||
}
|
||||
|
||||
function pugRenderer(viewsPath: string) {
|
||||
return async (c: Context, next: () => Promise<void>) => {
|
||||
c.pug = (template: string, locals: Record<string, any> = {}) => {
|
||||
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<string, any> = {}) => {
|
||||
const filePath = path.join(viewPath, `${template}.pug`);
|
||||
const html = renderFile(filePath, locals);
|
||||
return c.html(html);
|
||||
};
|
||||
});
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
export { pugRenderer };
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user