Javascript custom template engine Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript custom template engine without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to create a custom template engine in javascript but I’m having trouble getting started as I cannot extract tokens using regex.
Here are the requirements:

  1. Variables are defined like this: $(variable)
  2. Functions: $(name arg1 "this is arg2 but it contains whitespaces.")
  3. Function arguments can contain other variables $(name $(variable) arg2)

Both variables and functions will be rendered async. For example: Get the value for $(variable) from db then replace it.

This is not for rendering an html page but to simply replace a string entered by a user on the backend.


More information:
Suppose a user enters the following string:
$(id $(lowercase John))
On the backend application must do:

  1. Convert “John” to lowercase.
  2. Get the id for “john” from db.

This is only a simple example to demonstrate how this should work.

Are there any libraries that can help me achieve this? If not, any idea how to implement this?

I tried using Mustache and I changed the delimiters to $(), however the function (section) tags do no satisfy the requirements. In Mustache, for functions I must do this: $(#name) $(variable) "this is arg2 but it contains whitespaces."$(/name) also it does not support async rendering.


Other answers on this post are correct, however, I want to share exactly how I managed to implement this:

  1. Create a recursive match function. I used Steven Leviathan’s article to implement this.

  2. Create a render function and inside the function call the recursive match function to find and replace variable/function names with appropriate values.

  3. Keep calling the render function recursively until all arguments inside a function have been replaced.

We are here to answer your question about Javascript custom template engine - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji