FAQ: Learn Handlebars - Using Handlebars expressions

This community-built FAQ covers the “Using Handlebars expressions” exercise from the lesson “Learn Handlebars”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Building Interactive JavaScript Websites

FAQs on the exercise Using Handlebars expressions

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

This question really could apply to most of the Handlebars lesson and the Musicon project. After completing this exercise, I wanted to see if I could play with variations in syntax, but some variants were not successful and I’m not sure why. The first block below is my functional JS code written by following the directions completely:

const source = document.getElementById('greet').innerHTML;
 
const template = Handlebars.compile(source);
 
const context = {
  greeting: 'Hello World!'
}
 
const compiledHtml = template(context);

const fill = document.getElementById('hello');
 
fill.innerHTML = compiledHtml;

Since the variable source references the innerHTML of the ‘greet’ element, I wanted to see if I could move .innerHTML to the fill variable declaration:

const fill = document.getElementById('hello').innerHTML;
 
fill = compiledHtml;

The above code did not work. I can intuit that the variables fill and source are used for different things, but I can’t explain why writing a script like above wouldn’t be functional, nor can I explain why it’s okay to assign the full path to innerHTML of ‘greet’ to source (I did successfully move innerHTML from the source declaration to the compile method argument). I would love to hear an expert explanation. Thanks!

3 Likes

Coming back to this months later, it’s pretty obvious to me now. The parser would interpret my code as reassigning the const variable fill… not allowed. If I ran this with the javascript console up, I’m sure it would throw an error.

1 Like

Hello, I’m a bit confused with this exercise in Steps 7 & 8. I’m not exactly sure why we need to create the variable fill (where the code reads the following):

const fill = document.getElementById('hello');

fill.innerHTML = compiledHtml;

Edit for clarification: I’m adding in the full code from the exercise below. Here is the HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hello World!</title>
    <link type="text/css" rel="stylesheet" href="public/style.css">
    <script src="handlebars.min.js"></script>
    <!--Create a new script element on the line below-->
  </head>
      <script id='greet' type='text/x-handlebars-template'>
      {{greeting}} We salute you in peace.
      </script>
  <body>
    <div class="container">
      <h1>Handlebar Expressions</h1>
      <div id="hello">
      </div>
      <div class="blinker">|</div>
    </div>  
    <script src="public/main.js" type="text/javascript"></script>
  </body>
</html>

And here is the JS:

const source = document.getElementById('greet').innerHTML;

const template = Handlebars.compile(source);

const context = {
  greeting: 'Hello World!'
};

const compiledHtml = template(context);

const fill = document.getElementById('hello');

fill.innerHTML = compiledHtml;

I noticed in the example provided in the lesson they skip this step (the text just reads):

const source = document.getElementById('foo').innerHTML;

const template = Handlebars.compile(source);

const context = {
  bar: 'Text of the paragraph element'
};

const compiledHtml = template(context);

What is the purpose of fill?

Hi guys, I got stuck in step 6, the editor won’t let me go and I don’t understand why, here’s my code, please help and thanks in advance!:

const source = document.getElementById('greet').innerHTML;

const template = Handlebars.compile(source);

const context = {
  greeting: 'Hello World!',
};

const compiledHTML = template(context);
1 Like

Hey, I think that now you must have found the awnser but in your code you wrote HTML and not Html, thats why it won’t let you go

1 Like

Thank you! That’s right!

I have a question regarding Handlebars templates. What’s the advantage of using them?

I mean it seems there is so much fuss involved in getting them to work compared to pure JS code. Below I’ve typed a function that accomplishes the same:

const wordReplacer = (className, nuWord) => {
  const array = document.getElementsByClassName(className);
  for (let element of array) {
    element.innerHTML = nuWord;
  }
};

wordReplacer('flavor', 'Raspberry');

wordReplacer('name', 'John');  // it takes a one-liner to invoke the function again and again

Function above targets every the word or fragment tagged with <span class="flavor"><span> within the document/s. Now, I know that it’s not as neat as four curly brackets, but you only have to type it once and then you can just ‘copy and paste’.

Advantages:

  • function can be reused without retyping - just type in new class to target and new word to insert,
  • you can edit and format your page with your text where it belongs (between the <body> tags),
  • your class names can be shared across the pages and you can use them for custom styling too
  • if for some reason CDN link doesn’t work, you are not losing an entire paragraph/chunk of you page.
3 Likes

Followed the instruction step by step as per the material, it did not work at all!!!

8.

It’s time to add the compiled template HTML to the web page.

Assign compiledHtml to fill ‘s innerHTML property.

Once you pass the checkpoint, the browser will render ‘Hello World!’.

NO !!! NO HELLO WORLD SHOWS UP !!!

I can’t see any of its said benefits too.

1 Like

I was stuck with the exact same question. Then I found this beautiful post on stack overflow.

You are welcome :wink:

2 Likes

Thanks for your reply, but I still don’t see how this applies to Handlebars specifically. I agree that jQuery (as explained in the thread you posted) can make coding noticeably easier, but my original post wasn’t about questioning the functionality of all libraries out there. The majority of them come with concrete benefits - jQuery being one of them.

But I still can’t see how Handlebars (at least within the scope demonstrated in this course) make your job easier. You still have to write similar code (logic), but instead of keeping it in a separate JS file one places it into HTML, while still having to put some boilerplate code in JS. Again, perhaps I’m missing something important here but personally I find it messy, as it adds to the ‘clutter’ without offering significant benefits.

1 Like

You don’t actually need it.
I tried this and it works just as well:

document.getElementById('hello').innerHTML = compiledHtml;

I am guessing the course is trying to ‘isolate’ the steps in distinct variables.
That way, it breaks down the theory and helps us understand it better.

1 Like

do we have to take exact same object key as placeholder name ??

likewise, i couldn’t see Hello World being displayed, i thought im doing something wrong but crossed checked my code everything is intact

Did not have a problem completing any step of this exercise per the instructions, but still have absolutely no idea what the purpose of using Handlebars is.

The StackOverflow post that keeps getting shared contains one characteristcally sarcastic and dismissive answer, and one other answer that makes a case for 1. jQuery and 2. Libraries in general, but no case at all for Handlebars in this context, where it seems to be five times more convoluted and unwieldy than VanillaJS.

I also was unclear about the utiltiy of handlebars js and had the same question you did when I found a blog post which makes the case. Here is the link

I only skimmed it, but my takeaway is that handlebars keeps your code cleaner by reducing the intermingling of HTML and javascript elements.

Here’s an excerpt from the post:

If you develop or plan to develop JavaScript applications, you should use a JavaScript client-side templating engine to keep your JavaScript and HTML sufficiently decoupled; that is, keep your HTML separate from your JavaScript, which allows you to manage your HTML and JS files reliably and easily

Sure, you can use JSDom, or you can fire up server-side templating and send your HTML files via HTTP. But I recommend client-side templating because it typically executes faster than server-side templating and it provides the easiest way to create and maintain your templates.

In addition, just about all the JavaScript front-end frameworks use a JavaScript templating engine, so you will eventually use JavaScript templating because you will likely use a JavaScript front-end or backend framework.

Don’t know if you saw my reply about the purpose of handlebars. If not, thought you might be interested. FAQ: Learn Handlebars - Using Handlebars expressions - #18 by alphabaron

Instead of using handlebars to type something, isn’t it way easier and faster to use something like this:

<!--Your HTML-->
<h1>This is a heading that talks about the <span class="theme">Sky</span></h1>
<p>This is a paragraph that talks about the <span class="theme">Sky</span>

//Your app.js
document.getElementsByClassName("theme").innerHTML = "Ocean";

If I wrote the code right, the JavaScript file should look for all elements inside the HTML file with the “theme” class, and type whatever word you want to be in its place.