5

I am trying to create a super simple JavaScript templating solution. I want to use the JavaScript replace method to find all instances of curly braces in a template and replace them with their appropriate data.

For instance, if my template was: <p>My name is {{name}}. I am {{age}}.</p>

I would want the result: <p>My name is Olly. I am 19.</p>

Here's my code so far: http://jsfiddle.net/2RkAG/

I'm trying to make it automatically replace each piece of data, so I don't have to explicitly tell the JavaScript what to replace. However, this is where I am having problems.

1 Answer 1

4

$1 only works if you pass a string directly. It does not work the way you have it, because person["$1"] is evaluated before the string is passed to .replace - and person["$1"] literally is undefined.

You can pass a function instead: http://jsfiddle.net/2RkAG/1/. The function is called for each replacement and has arguments passed that are equivalent to e.g. $1.

$result.html(template.replace(/{{(.*?)}}/g, function(a, b) {
    return person[b]; // a = complete match, b = first group
}));

You don't need to escape the first {, either.

Sign up to request clarification or add additional context in comments.

3 Comments

Say, what if I want to use the template like so: <p>My name is {{person.name}}. I am {{person.age}}.</p>. I have got this working with eval, but is this the best way to do this? Safe? Like so: jsfiddle.net/2RkAG/20
@Oliver Joseph Ash: You'd need some path finding algorithm if you don't want eval: jsfiddle.net/2RkAG/24.
@OliverJosephAsh - the safety of eval() depends upon the safety of the input. If it's just your own code in the templates, then you can trust that the input won't be nefarious. If the input is not under your control, then it could be used to inject arbitrary code into your page and you have to assess the impact of that. Sometimes that has no real risk (the user can generally inject code into their own page anyway) and sometimes it does have risk - it depends.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.