Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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