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

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>