-1

I know the Fresh framework is in its early stages of development and that by default comes with Preact for rendering anything. But also, I've heard that Fresh is meant to be framework agnostic. My eventual goal is to create a framework that competes with Preact and JSX, but for the time being I'm just looking to render static HTML as strings. I haven't found anything about this online. As a proof of concept I'm trying to do something like this:

// index.ts
export default `<h1>Title</h1>`;

But I end up with the following error:

An error occurred during route handling or page rendering. Error: 
<h1>Title</h1> is not a valid HTML tag name in <<h1>Title</h1> params="
[object Object]" url="http://localhost:8000/" route="/">`

Is there any way to achieve this?

jps
  • 20,041
  • 15
  • 75
  • 79

1 Answers1

4

I've heard that Fresh is meant to be framework agnostic

Fresh very much uses, relies on, and promotes usage of Preact. "The framework [Fresh] uses Preact and JSX (or TSX) for rendering and templating on both the server and the client" (Fresh 1.0). (See also Fresh 1.1 - automatic JSX, plugins, DevTools, and more.)

// index.ts
export default `<h1>Title</h1>`;

Your example here doesn't work because a string is not a valid JSX.Element (or in Preact terms, it is not a valid VNode).

In a Fresh project, the example HTML can be rendered as follows using Preact with JSX (or TSX):

// index.ts
export default () => <h1>Title</h1>;

This can also be done using Preact without JSX (or TSX):

// index.ts
import { h } from "preact";

export default () => h("h1", { children: "Title" });

To return raw HTML without using Preact or JSX (or TSX) you can use Fresh's route middleware:

// index.ts
export const handler = () =>
  new Response(`<h1>Title</h1>`, { headers: { "Content-Type": "text/html" } });

One way to simplify doing this in various places is to define a tag function and use tagged templates:

//index.ts
import html from "../utils/html-tag.ts";

export const handler = () => html`<h1>Title</h1>`;
//../utils/html-tag.ts
export default function html(
  strings: TemplateStringsArray,
  ...values: unknown[]
) {
  const body = String.raw({ raw: strings }, ...values);
  return new Response(body, { headers: { "Content-Type": "text/html" } });
}
mfulton26
  • 29,956
  • 6
  • 64
  • 88