Your resource for web content, online publishing
and the distribution of digital products.
S M T W T F S
 
 
 
 
 
1
 
2
 
3
 
4
 
5
 
6
 
7
 
8
 
9
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
 
23
 
24
 
25
 
26
 
27
 
28
 
29
 
30
 

Vanilla JS Server Side Rendering

Tags: api
DATE POSTED:October 2, 2024

\

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 `

My number is: ${t}

` }), ); }} // output: Here is my headings: //

My number is: 1

My number is: 2

My number is: 3

My number is: 4

My number is: 5

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 `

${t.data}

` }), )), ); }} ` 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 `

${t.data}

` }), )), ); }} `

\

Tags: api