8

I am using node.js. I want to read a file with some placeholder strings and replace them dynamically before I serve the file. This is not an HTML file, so a templating engine will not work.

How can I do this?

2
  • I've tried loading the file as a string and doing regex replace. Was wondering if there is a more elegant way though. Commented Mar 1, 2011 at 5:17
  • 1
    have you tried mustaches? mustache.github.com Commented Mar 1, 2011 at 7:07

2 Answers 2

24

If a template engine is overkill just use string.replace().

temp = "Hello %NAME%, would you like some %DRINK%?";

temp = temp.replace("%NAME%","Michael Dillon");
temp = temp.replace("%DRINK%","tea");
console.log(temp);

With only a bit more work you could make a general purpose template function based on just the standard methods in the String object.

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

Comments

2

Templating engines are not only for html. If you are using Express, for instance, you can set your own headers and specify a content-type:

View:

var foo = "{{ bar }}";

Rendering:

app.get('/file.js', function(req, res, next) {
  res.render('templateName', {
    locals: {bar: 'quux'},
    headers: {'content-type': 'text/javascript'}
  });
})

Will yield:

var foo = "quux";

If you are not using Express, you can just render the template and send the response with any content-type you like.

Comments

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.