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

over ride the filecontents variable.

I'm a little bit confused. approximately on minute 4:10 Andrew replaced the content of the variable fileContents. I didn' understand what he was doing. I marked the appropriate line with an arrow. Thanks!

function view(templateName, values, response) { // Read from the template file

let fileContents = fs.readFileSync('./views/' + templateName + '.html'); // Insert values in to the content --------> fileContents = mergeValues(values, fileContents);

response.write(fileContents);

//, (err, data) => { // if (err) throw err; // response.write(data); // });

}

1 Answer

He is reassigning the value of the fileContents.

He is using the mergeValues function to do this. The mergeValue takes two arguments

  1. The values for the profile
  2. The current value of fileContents. (The html we are rendering to the browser)

What he is doing is, passing in the html page and the values that need to be displayed on the page. The mergeValues function is going to update the html page with those values, and assign it back to fileContents. In essence, fileContents will still be the same, accept now it will have the placeholders for our values replaced with the actual values to display.

Example: Before passing fileContents to the function, the profile.html contents had this section.

<p><span>@{{username}}</span></p>

After reassigning the return value of the mergeValues to fileContents to, the same section now looks like this

<p><span>@Waldo</span></p>