The question is published on by Tutorial Guruji team.
Here are the requirements:
- Variables are defined like this:
$(name arg1 "this is arg2 but it contains whitespaces.")
- 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.
Suppose a user enters the following string:
$(id $(lowercase John))
On the backend application must do:
- Convert “John” to lowercase.
- 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:
Create a recursive match function. I used Steven Leviathan’s article to implement this.
Create a render function and inside the function call the recursive match function to find and replace variable/function names with appropriate values.
Keep calling the render function recursively until all arguments inside a function have been replaced.