Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

JavaScript templating with mustache.js

From: JavaScript and JSON

Video: JavaScript templating with mustache.js

Mustache.js is a logicless template library that let's you flow JSON data onto an existing page. You can have as many templates as you want on a page, so you can take the same JSON data and display it in different ways. Using the library couldn't be easier. You create a template and then bring the JSON file and flow it into an area of your page using the template as a guide. Want to know more about mustache? Make sure you check out this website or download the library directly from github. I'm going to go my document, and onto my server I have loaded a couple of additional files.

JavaScript templating with mustache.js

Mustache.js is a logicless template library that let's you flow JSON data onto an existing page. You can have as many templates as you want on a page, so you can take the same JSON data and display it in different ways. Using the library couldn't be easier. You create a template and then bring the JSON file and flow it into an area of your page using the template as a guide. Want to know more about mustache? Make sure you check out this website or download the library directly from github. I'm going to go my document, and onto my server I have loaded a couple of additional files.

You can see that I have an images folder with some images that I'm going to use later on, coming from the template as well as a data.json template. I've got this one open right here. You can see that it is a speakers object, and the speakers object has an array of element. You could see it right here. It's always a good idea to make sure that when you create a JSON document it's formatted perfectly, or you won't be able to do anything with it. Let me go ahead and copy this, and I'm going to switch over to the JSON Editor Online. And what I want to do is paste that right here, then hit this button.

That button will move it over from this side into this side. Here I can make sure that I take a look at the structure of my objects. I know this is one object called speakers. It has nine elements and if I expand that, I can see each element and expand any of the elements to see what the structure would be. Now, I know that my JSON file is fine because it would've shown me an error if it wasn't formatted properly, so that's great! Let's go ahead and go into our index file and first create the template that we're going to use to display this data.

The template looks a lot like a regular script, so we're going to type in a script tag. It's not going to have a source, and the type is not going to be text/javascript. It's going to be text/template. I need to add an ID so that I can target this later with mustache.js. Add an ID of speakerstpl for template and now we're ready to create our template. Our template is going to look at lot like regular HTML. As a matter of fact, it is going to be HTML, with some additional little placeholders for our data.

First off, I'll start by creating a placeholder for the speakers, and I'll put a pound sign right here. So this is the first part of the template. I need to close it, kind of like how I close an HTML element. Now, where am I getting this from? This actually comes from my data file, and it's the name of my object. So what mustache is going to do is it's going to cycle through all the speakers in my object and apply the template that I'm going to type in here. I'll create a div with a class of speaker, and I'm going to close that just like I would any other div. Then I'm going to add an image src.

It is going to be my images folder, and then the name that I call here, shortname, as well as _tn.jpg. Where am I getting this from? That is the name of one of these elements called shortname. Shortname is pretty much the name up here without any special characters, so it has an underscore instead of a space. That's how my images are named. If you open up my images, you'll see that Barot is named with his short name, plus _tn.jpg, and that's what I'm doing here.

I'll add an Alt tag, and in here I'll pull in the name of this user. You can probably tell why the library is called mustache.js. It uses these little curly brackets that look like mustaches on their side, and it uses these as placeholders to target different JSON elements in your files. Now, we'll type in an h3. We'll also need an h4, so I'll do that one as well. And that will have the name and this other one will have the reknown.

Finally, we'll do a paragraph and that will have the bio. These are all names of fields in our data.json document. And the template is really nothing more than just HTML with the placeholders for the template. Now, we need to create another script. This one has to go after the libraries load, because this is going to use these libraries and this is going to be a normal script, so it's not going to refer to an external file.

Here we'll start off by doing that function that executes whenever jQuery loads. In here, we'll use jQuery's getJSON function. That's going to load our data file, and when that data file is received, then it's going to execute a function literal. It's going to read the contents of data.json into a data object.

We'll create a variable called template. That variable is going to load the contents of the template that we created up here. I'm going to use jQuery to target the speakerstpl, which is what I call the template up there, and read the HTML into this template variable. Here's the part where I'm actually going to use mustache.js. I'm going to create an HTML variable, and into that variable I'm going to call the mustache.to_html function for mustache.js, and feed that the template that I read into the template variable, as well as the data that we received from the JSON file.

Mustache to HTML will process the data and feed it into the template and then create some HTML. Once we have that HTML, then we can feed it into a div. We created the div with an id of carousel to feed that data into, and so we'll modify its HTML to be the HTML that we received from mustache.js. So, this id right here is referring to this div id right here. It's going to feed all that data into that. If we did everything correctly, I'm going to save this, and I'm going to come into my page and I'll refresh it, and we should see all the data from our JSON file fall in here.

It's not just the data. It's actually the data formatted in the template that we chose. If we select Inspect Element, you can see that this one gets an h3, the sub-headline gets an h4, and our paragraph is right there as well. JavaScript templating is one of those techniques that makes your life a lot easier. Once you know how to flow data into your page using JSON templates, you'll be able to build websites more efficiently.

Show transcript

This video is part of

Image for JavaScript and JSON
JavaScript and JSON

19 video lessons · 19441 viewers

Ray Villalobos
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript and JSON.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.