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 Binding Values

Duy Khanh
PLUS
Duy Khanh
Courses Plus Student 4,911 Points

I can not bind the value ? Help me

I dont know what wrong in my code , i can not bind the value

var fs = require("fs");

function mergeValues(values, content) {
  //Cycle over the keys
  for(let key in values) {
    //Replace all {{key}} with the value from the values object
    content = content.replace(`{{${key}}}`, values[key]);
  }
  //return merged content
  return content;
}

function view(templateName, values, response) {
  //Read from the template file
  var fileContents = fs.readFileSync('././view/' + templateName + '.html', {encoding: "utf8"});
  //Insert values in to the content
  fileContents = mergeValues(values, fileContents);
  //Write out the contents to the response
  response.write(fileContents);
}

module.exports.view = view;

1 Answer

I think the issue is with this line:

var fileContents = fs.readFileSync('././view/' + templateName + '.html', {encoding: "utf8"});

I think your path to the html file is off. Are you actually getting the correct fileContents from this?

Duy Khanh
Duy Khanh
Courses Plus Student 4,911 Points

i make a folder name module inclue render.js and the view in another so i put ././ is not right ?

What is your directory structure? If you want to step out of your current folder you need to do ../ and ./ means in the current folder