Javascript custom template engine

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.