Vanilla JS Server Side Rendering

TL;DR (Too Long Didn't Read)

Function

const render = async (x, ...values) => {
  var rendered = "";
  for (let u = 0; u < x.length; u++) {
    rendered = rendered.concat(x[u]);
    if (u < x.length - 1) {
      if (typeof values[u] == "function") {
        var res = await values[u]()
        if(res) rendered += res;
      } else {
        rendered +=values[u]
            }
    }
  }
  return rendered;
};

Usage

const result = render`My string is = ${()=> {return (1 + 1)}}`

console.log(result)
// output -> My string is 2

What Is This?

By render, I meant being able to run async and sync functions inside of a string. Which may be called templating.

This is a basic function which uses template literals, it can run the functions inside of a string which lets us to do many things like, retrieve data from database, fetch data from an API, calculate stuff which is provided earlier and so on.

How it works

You may understand what it does from the code above if you have prerequisite knowledge about tagged templates, it just runs the functions and put the output of function in the place where function executed.

Warning

In many times using async functions inside async functions inside async functions are required and without using proper async await functionality, this stuff is getting too error prone. It may return [Object Promise][Object Promise][Object Promise]. With a simple Promise.all(), we can fix all of that.

Promise.all()

Examples below.

Rendering list

Just like react, we will use .map() function.

await render`
    Here is my headings:
    ${() => {
      return "".concat(
          ...[1,2,3,4,5].map((t) => {
            return `<h1>My number is: ${t}</h1>`
          }),
      );
    }}
// output: Here is my headings:
// <h1>My number is: 1</h1><h1>My number is: 2</h1><h1>My number is: 3</h1><h1>My number is: 4</h1><h1>My number is: 5</h1>

Examples

Retrieve data from DB

Promise.all() here is not necessary because there is no asynchronous function inside them

await render`
Here is my data
${async () => {
  const text = `SELECT * FROM table`;
  const values = [];
  var record = await pool.query(text, values);
  return "".concat(
    ...(await Promise.all(
      record.rows.map((t) => {
        return `<h1>${t.data}</h1>`
      }),
    )),
  );
}}
`

Fetch data from api

await render`
Here is my data
${async () => {
  const res = fetch("https://example.com", {method:"GET"})
  const data = await res.json()
  return "".concat(
    ...(await Promise.all(
      data.first.map((t) => {
        return `<h1>${t.data}</h1>`
      }),
    )),
  );
}}
`