Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Creating a Basic Template Engine in Node.js A Simple Merge Utility

Aashish Tripathi
Aashish Tripathi
1,151 Points

I could not get to complete Challenge Task 1 of BUILD A SIMPLE DYNAMIC WITH NODE.JS

I am not sure how to implement the merge in utilities.js

index.js
var utilities = require("./utilities");

var mailValues = {};

mailValues.first_name = "Janet";

var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";

var mergedContent = utilities.merge(emailTemplate, mailValues);

//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
utilities.js
function merge(content, values) {
  var key = "$first_name%";
//for(key in content)
  //  {
  content = content.replace("{{" + key + "}}", values);
//}
  return content;
}


module.exports.merge = merge;

2 Answers

You're following along with the video, but the exercise wants you to replace a key within percent signs rather than within double curly brackets. You had it right with the for loop that you commented out -- uncomment it, then replace your double curlies with percent symbols. Also remember, values is an object as well, so you need to tell the method which value to replace the key with.

  content = content.replace("%" + key + "%", values[key]);

Also -- you don't need to declare the key variable at the top. If you do that, then the program isn't dynamic. The way the for loop works is it looks for all of the keys within the content object. This way, if you included '%last_name%' you'd be able to dynamically merge that as well.

Aashish Tripathi
Aashish Tripathi
1,151 Points

Hi Galen, Thanks for your response. However, there's still some problem with the code. Following is the snippet that I tried, but it doesn't work too. I was hoping to get some help over here.

Here's my utilities.js

function merge(content, values) {
  for(var key in content)
  {
    content = content.replace("%" + key + "%", values[key]);
  }
  return content;
}
module.exports.merge = merge;

I had a problem with this too, You're only one word off! Hint: you're trying to use the for loop to iterate through the keys of content when it should be iterating through the keys of ....