Template View

Posted by Dustin Boston .

The Template View renders content by embedding “markers” within a static HTML template. These markers get replaced at runtime with data provided by a helper object. The helper encapsulates logic for getting and formatting the related data. This approach separates the presentation layer from the application logic. This way, designers can work on the HTML without needing to write code.

Source Code Listing

code.ts

/**
 * Helper class that provides data for the template view.
 */
export class BookHelper {
  private title: string;
  private author: string;

  constructor(title: string, author: string) {
    this.title = title;
    this.author = author;
  }

  getTitle(): string {
    return this.title;
  }

  getAuthor(): string {
    return this.author;
  }
}

/**
 * Template function (template view) - renders HTML using the BookHelper.
 * @param helper - An instance of BookHelper that provides data for the template.
 * @returns A string containing the rendered HTML.
 */
export function renderTemplate(helper: BookHelper): string {
  return `
    <html>
      <body>
        <p><b>${helper.getTitle()}</b></p>
        <p>Author: ${helper.getAuthor()}</p>
      </body>
    </html>
  `;
}

/**
 * @example Start the server
 * bun run code.ts
 *
 * @example Test the endpoint
 * curl -X POST "http://localhost:3000/"
 */
Bun.serve({
  routes: {
    "/": (_req) => {
      // Create a helper object with dynamic data
      const bookHelper = new BookHelper(
        "The Great Gatsby",
        "F. Scott Fitzgerald",
      );

      // Render the template with the helper
      const html = renderTemplate(bookHelper);

      // Send the rendered HTML as the response
      return new Response(html, {
        headers: {"Content-Type": "text/html"},
        status: 200,
      });
    },
  },
});