Temple Logo

Temple

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 Temple, 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.dtml package.json
src
index.ts page.dtml package.json
import http from 'http'; import temple from '@ossph/temple/compiler'; //create temple compiler const compiler = temple({ 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.dtml', { title: 'Hello World' })); } }); //listen on port 3000 server.listen(3000);
The server file src/index.ts implements a simple server utilizing the Temple compiler in its most simplistic form. The document file src/page.dtml is using the most basic Temple 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.