DenoCitizen
DenoCitizen•3mo ago

Take data from a ts file to display it in the html

How can I take data from a ts file to display it in the html? Like a search bar. Is it possible to do this in Deno Fresh? Thanks in advance
2 Replies
Deno AI Helper
Deno AI Helper•3mo ago
Yes, it is indeed possible to take data from a TypeScript file and display it in HTML within a Deno Fresh application. Fresh provides a way to handle server-side rendering and pass data to the front end. Here's a step-by-step explanation based on the documentation: 1. Define your data and handlers in a TypeScript file: You can create a TypeScript file that exports a handler object with methods corresponding to HTTP methods like GET, POST, etc. This handler can process requests and pass data to the rendering function. 2. Create a server-side handler: In your route handler, you can define a GET method that processes the request, extracts any necessary data (like query parameters), and then passes that data to the rendering function. 3. Render the data in your page component: The data passed from the handler can be accessed in your page component as props. You can then use this data to dynamically generate your HTML. Here's an example from the documentation that demonstrates how to implement a search bar: ```typescript import { Handlers, PageProps } from "$fresh/server.ts"; const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"]; interface Data { results: string[]; query: string; } export const handler: Handlers<Data> = { GET(req, ctx) { const url = new URL(req.url); const query = url.searchParams.get("q") || ""; const results = NAMES.filter((name) => name.includes(query)); return ctx.render({ results, query }); }, }; export default function Page({ data }: PageProps<Data>) { const { results, query } = data; return ( <div> <form> <input type="text" name="q" value={query} /> <button type="submit">Search</button> </form> <ul> {results.map((name) => <li
Deno AI Helper
Deno AI Helper•3mo ago
key={name}>{name}</li>)} </ul> </div> ); } `` In this example, when the user submits the form, the browser navigates to the search route with the query set as the q query parameter in the URL. The GET handler then filters the NAMES` array based on the query and passes it to the page component for rendering. Remember to include the necessary imports at the top of your TypeScript file and to follow the conventions of Fresh for defining routes and handlers. 🦕