Readme

Pug HTML Template Renderer

This function is equivalent to pug.render - it takes a Pug template string and renders it to an HTML string. import(npm:pug) doesn't work in Val.Town due to Pug's usage of new Function, which is forbidden for security reasons, so this function uses Val.Town's eval API instead.

Example

const myEndpoint = async (req: express.Request, res: express.Response) => { const html = await @wilt.pug("p Hello #{name}!", {name: "Pug"}); res.status(200); res.send(html); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { fetch } from "https://esm.town/v/std/fetch";
export async function pug(
templateStr: string,
args = {},
// Not sure why anyone would use this callback, but it's included for compatibility with pug.render
callback = ((html: string) => html),
): Promise<string> {
const pugLexer = import("npm:pug-lexer");
const pugParser = import("npm:pug-parser");
const pugCodegen = import("npm:pug-code-gen");
const lexer = new (await pugLexer).Lexer(templateStr);
const parser = new (await pugParser).Parser(lexer.getTokens());
const { default: genCode } = await pugCodegen;
const pugFnStr = genCode(parser.parse(), { inlineRuntimeFunctions: true });
const evalResp = await fetch("https://api.val.town/v1/eval", {
method: "POST",
body: JSON.stringify({
code: `(args) => { ${pugFnStr} return template(args); }`,
args: [args],
}),
});
const renderedHtml = (await evalResp.text()).trim().slice(1, -1);
return callback(renderedHtml);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023