1

How to get effect like this?

name = 'Mark';
template = 'Your name is {{name}}';
console.log(template); // return "Your name is Mark";
name = 'John';
console.log(template); // return "Your name is John"

How to make some kind of easy template system for strings? Maybe function that will find for some tags ( {{ }} for example) and replace text inside with current variable? Or some method that is build in JS?

3
  • 1
    No need to make one, it already exists ~ developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented May 4, 2017 at 0:44
  • @Phil A template string is different than this, where the template string itself can be anything the user defined. Commented May 4, 2017 at 1:09
  • Fair point, the template literals aren't an interpolation engine Commented May 4, 2017 at 1:13

2 Answers 2

3

Try mustache. https://mustache.github.io/mustache.5.html

A typical template would look like this:

Hello {{name}}
You have just won {{value}} dollars!

The same (custom-templates) can be achieved using react as well, but react uses javascript code in single {} curlies. This allows u to fit logic around ur (template) components. They become reusable across views.

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

Comments

2

I created a very simplified templating function if you really need it to be dynamic. I don't recommend using this for a production site, as there are templating engines like handlebars, mustache, dust, etc, but this may work for you. You can test it out at this fiddle: https://jsfiddle.net/vw6av0am/

function templateMe(template, obj) {
  var regex = /{{(.*?)}}/g;
  return template.replace(regex, function(match, capture) {
    return obj[capture] || "";
  });
}

var template = 'Your name is {{name}}';
var obj = {
  name: "Mark"
};

var output = templateMe(template, obj);
console.log(output);

1 Comment

In case anyone's interested, I made an update to allow for nested attributes in the object you're passing in: jsfiddle.net/vw6av0am/1

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.