Template Engine

Template engines are used when you want to rapidly build web applications that are split into different pages. Templates also enable fast rendering of the server-side data that needs to be passed to the application. You can use Ink, TypeScript and the native Node.js HTTP server to serve up HTML documents from the server-side. First, create a project with the following structure and files.
src/index.ts src/page.ink package.json
src
index.ts page.ink package.json
import http from 'http'; import ink from '@stackpress/ink/compiler'; //create ink compiler const compiler = ink({ cwd: __dirname }); //create http server const server = http.createServer(async (req, res) => { //if build asset... if (req.url?.startsWith('/build/')) { //get filename ie. abc123.js const filename = req.url.substring(7); //get asset const { type, content } = await compiler.asset(filename); //send response res.writeHead(200, { 'Content-Type': type }); return res.end(content); //if home page } else if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end(await compiler.render('./index.ink', { title: 'Hello World' })); } }); //listen on port 3000 server.listen(3000);
The server file src/index.ts implements a simple server utilizing the Ink compiler in its most simplistic form. The document file src/page.ink is using the most basic Ink syntax. To test the script and see the results, run the following command in terminal. npm run dev Load http://localhost:3000/ in your browser to see your application.