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

Edwin Carbajal
Edwin Carbajal
4,133 Points

Key values not being rendered in view files :(

When i search for a user, the template uses {{key}} instead of its actual value. This is the renderer.js file

const fs = require('fs');

const mergeValues = (values, content) => {
  // cycle over the keys
  for(const key in values) {
    // replace all {{keys}} with the valye from the values object
    content = content.replace(`{{ ${key} }}`, values[key]);
  }

  // return merged content
  return content;
}

const view = (templateName, values, response) => {
  // read from the template files
  const fileContents = fs.readFileSync(`./views/${templateName}.html`, {encoding: 'utf-8'});
  // insert values in to the content
  fileContents = mergeValues(values, fileContents);
  // write out the contents to the response
  response.write(fileContents);
}

module.exports.view = view;

And this is the router.js file

const Profile = require("./profile.js");
const renderer = require("./renderer.js");

// Handle HTTP route GET / and POST / i.e Home
const home = ((request, response) => {
  // if url == '/' && GET
  if(request.url === '/') {
    // show search
    response.statusCode = 200;
    response.setHeader('Content-Type', 'text/plain');
    renderer.view('header', {}, response);
    renderer.view('search', {}, response);
    renderer.view('footer', {}, response);
    response.end();
  }
  // if url == '/' && POST
    // redirect to /:username
});

// Handle HTTP route GET /:username i.e /chalkers
const user = ((request, response) => {
  // if url == '/....'
  const username = request.url.replace("/", "");
  if(username.length > 0) {
    response.statusCode = 200;
    response.setHeader('Content-Type', 'text/plain');
    renderer.view('header', {}, response);

    // get json from Treehouse
    const studentProfile = new Profile(username);
    // on 'end'
    studentProfile.on('end', (profileJSON) => {
      // show profile

      // store the values which we need
      const values = {
        avatarUrl: profileJSON.gravatar_url,
        username: profileJSON.profile_name,
        badgeCount: profileJSON.badges.length,
        javaScriptPoints: profileJSON.points.JavaScript
      }
      // simple response
      renderer.view('profile', values, response);
      renderer.view('footer', {}, response);
      response.end();
    });

    // on 'error'
    studentProfile.on("error", (error) => {
      // show error
      renderer.view('error', {errorMessage: error.message}, response);
      renderer.view('search', {}, response);
      renderer.view('footer', {}, response);
      response.end();
    });
  }
});


module.exports.home = home;
module.exports.user = user;

1 Answer

Kayla Kremer
Kayla Kremer
14,269 Points

Hello :)

I think your problem lies in your for loop. Instead of using const for the key, try let instead since const declarations cannot be reassigned in each loop iteration. Also, remove the extra spaces between the double curly brackets and ${key}. This worked for me:

const mergeValues = (values, content) => {
  for (let key in values) {
    content = content.replace(`{{${key}}}`, values[key]);
  }
  return content;
};

Thank you, Kayla. Your answer was perfect. My problem wasn't that I used const instead of let. My problem was in my template literal where I was adding a space before and after ${key}

This did not work:

for (let key in values) {
    //replace all {{key}} with values from the values object
    content = content.replace(`{{ ${key} }}`, values[key]);
  }

This did work:

for (let key in values) {
    //replace all {{key}} with values from the values object
    content = content.replace(`{{${key}}}`, values[key]);
  }

It will never cease to amaze me the difference between working code and non-working code can literally be a spacebar click ;)