Easily generate formatted HTML source code programmatically using simple and flexible functions.
- Lightweight and easy to use.
- Generate clean, formatted HTML programmatically.
- Great for templating or dynamic HTML generation in TypeScript/JavaScript projects.
html
: Generate an HTML source document from theHtmlNode
, with options for:doctype
,indentText
, andinsertNewLines
.tag
: Generate an HTML tag, can have attributes and an arbitrary number of children nodes as arguments.raw
: Insert raw unescaped HTML.comment
: Generate an HTML comment.toHtml
: Convert an object value to anHtmlNode
.escapeHtml
: Escape HTML special characters in a string.
To install the library, use:
deno add jsr:@sander/html
npx jsr add @sander/html
bunx jsr add @sander/html
Here’s a quick example to get started:
import { assertEquals } from "@std/assert";
import { html, tag } from "./html.ts";
const page = html(
tag("html", [
tag("h1", "Welcome to HTML Generator"),
tag("div", { class: "banner" }, "This is an example of generated HTML."),
]),
{
doctype: "html",
},
);
assertEquals(
page,
`\
<!doctype html>
<html>
<h1>
Welcome to HTML Generator
</h1>
<div class="banner">
This is an example of generated HTML.
</div>
</html>
`,
);
For a longer example, check out example.ts
.
The ToHtml
interface with an toHtml
method can be used implement custom
types that can be converted to HTML.
import { type HtmlNode, tag, type ToHtml } from "@sander/html";
class Custom implements ToHtml {
constructor(public value: string) {}
toHtml(): HtmlNode {
return tag("div", { class: "custom" }, this.value);
}
}
This library can also be used inside the brower to generate HTML source code.
<script type="module">
import { escapeHtml } from "https://esm.sh/@jsr/sander__html/";
console.log(escapeHtml('<script>alert("xss")<' + "/script>"));
// output: <script>alert("xss")</script>
</script>
Although the browser has DOM manipulation APIs and there exists frontend frameworks that are better suited for interactive applications.
Contributions are welcome! Please submit an issue or open a pull request for bug fixes, new features, or documentation improvements.
This project is licensed under the MIT License.