create a html templating engine in javascript

To create a simple HTML templating engine using JavaScript, you can use string interpolation to dynamically generate HTML code with values passed from the server-side.

Here is an example using Node.js + Express.js:

First, create an HTML template file called "template.html" with placeholders like so:

<!DOCTYPE html>
<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
    <h1>{header}</h1>
    <p>{content}</p>
  </body>
</html>
139 chars
11 lines

In your server-side JavaScript code (using Node.js and Express.js), you can then read in this template file and replace the placeholder values with actual data:

index.tsx
// Require the necessary modules
const express = require('express')
const fs = require('fs')

// Create an instance of the express app
const app = express()

// Define a route that will render the HTML template
app.get('/', (req, res) => {
  // Read in the template file
  fs.readFile('template.html', 'utf8', (err, data) => {
    if (err) throw err

    // Replace the placeholder values with actual data
    const renderedData = data
      .replace('{title}', 'My Website')
      .replace('{header}', 'Welcome to My Website')
      .replace('{content}', 'This is the content of my website.')

    // Send the rendered HTML back to the client
    res.send(renderedData)
  })
})

// Listen on port 3000
app.listen(3000, () => {
  console.log('Server listening on port 3000...')
})
781 chars
29 lines

When a client makes a request to the server, the server will read in the "template.html" file, replace the placeholder values with actual data (in this case, hardcoded values), then send the resulting HTML back to the client.

Of course, this is just a simple example - in a real application, you would likely want to separate your HTML templates into multiple files, use a more robust templating engine, and fetch data from a database or other source instead of hardcoding it.

gistlibby LogSnag