JavaScript Template Literals: JSON to HTML

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone in this video we are going to learn about template literals we are going to answer questions like what is a template literal and when or why would I use one I'm going to answer these questions and a bit more of a roundabout fashion so if you're just looking for a quick 30 second or two minute explanation of template literals this is not the video for you instead of just an underwhelming hello world example we are going to work through a more real-world example together so here is a code pen that I've put together and I encourage you to use this so you can follow along with me okay and what is our goal what are we going to be building together well in the JavaScript column you can see we have a bit of JSON esque data right we've got an array with three objects in it and each object represents a pet you can see it contains their name their species their favorite food the year they were born and a URL to a photograph now our goal is to use this JSON data to generate HTML that looks like this so this is a sneak preview of the finished product of what you and I are going to be building and we're going to use template literals to generate this entire string of HTML including all of the looping and conditional logic that we're going to need it might take more than just a few minutes but it should be a lot of fun we're gonna learn a lot about template literals and really just JavaScript in general so without further ado let's get started let's begin by writing a bit of JavaScript to add a bit of HTML into this empty div so over in the JavaScript column you can scroll down to the very bottom and right after this closing square bracket and semicolon down here you can start typing and following along with me I'm going to jump into my text editor just so there's less on the screen and it's easier to see in this video but you can follow along and code pen okay so at the bottom of our JavaScript let's select empty div so document get element by ID and it had an idea of app and then if we want to change its HTML we can just say dot inner HTML now traditionally you might set this to equal a string of text right so quotes hello and that would output hello on to the page however instead of wrapping our text within quotes to create a simple string instead let's wrap it in back ticks using back ticks like this is how we tell JavaScript we want to create a template literal if you're looking for this character on your keyboard it's to the left of the one key or right above the tab key anyways the question becomes well what is a template literal for now just think of it as a string of text with superpowers so for example we can say hello two plus two equals blank and it always will now instead of the word blank here we could hard code this to the number four but instead if we want to do something dynamic if we want to run an expression we can just say dollar sign curly brackets and then whatever we want so two plus two and that will actually output for right that code is actually being evaluated so this lets us insert something dynamic within an otherwise static string of text now you might be thinking big deal who cares this is just interpolation and other programming languages have had this forever and that's true but historically javascript did not have a super easy intuitive way of achieving this so that's the first big superpower of template literals they let us include expressions within our strings of text okay now let's move on to the next superpower and that is that within a template literal you are free to drop down to new lines so as long as you're still within or for the closing backtick we could create a paragraph hi there and we could create another new line hello again and this is nice because this is how you would traditionally write HTML right each element gets its own line instead of something awkward like this now this might not seem like a big deal but historically in JavaScript with traditional strings of text so if we were using quotes instead of backticks you would need to escape each line break with a backslash like this that can be awkward and now our code doesn't look as clean but luckily with template literals you do not need the backslash escapes okay now if you add those two superpowers together interpolation with strings and multiple lines this creates the perfect recipe for outputting complex dynamic HTML so we are going to use those two superpowers to create this layout together now that we've got these basics out of the way let's dive back into our code and give ourselves a clean slate so let's delete this current template literal and create a brand new one right so just to back ticks and let's finally start building our project so let's begin with a heading level one and let's have it say pets and in parentheses we want it to say some blank number of results right but we don't want to hard-code this to a certain number because in the future there might be pets that get deleted from our collection or new pets could be added so in place of a number here let's include an expression remember we just say dollar sign curly brackets to do something dynamic within the curly brackets let's begin with the name of our array so back up at the top here remember the array that contains all of our pet data is named pets data with a capital D so within our curly brackets pets data and in JavaScript every array has a property named length which will return how many items live in the array so altogether this will output cool pets three results and just for styling or CSS reasons why don't we give our opening h1 tag a class of app - title and also just to stay organized why don't we drop down to a new line right in between the opening back tick and our h1 like this and then we can also drop down to a new line right before the closing back tick cool so this will give us a little bit of styling next up let's include a note to ourselves so on a new line we can say pets will go here and then below that let's include our footer right so a paragraph element let's say these 99 pets were added recently check back soon for updates right and again we don't want to hard-code this 299 we want a dynamic count of how many pets there are so dollar sign curly brackets our array is named pets data and we're interested in the length okay let's also give this opening paragraph a class of footer just for CSS reasons so that will output this now we've got our footer we've got our header we just need to work on the pets will go here section right if I look at the finished product we need a way to loop through the array and do something once for each pet or each item in our array now there are many different ways of doing this but let me show you what I think is the most elegant way so back in our code let's delete this pets will go here line and let's say dollar sign curly brackets and if we just type the name of our array so pets data just that alone will output this this is Java scripts attempt at displaying an array of objects as a string of text now there are two main issues here that we need to solve first we want to remove the commas in between each object right because if we look at our finished product we don't want after each animal and the other issue obviously is that we don't want each animal to be represented as just object object so we will solve both issues but first let's begin with the comma issue how can we get rid of these commas well first we need to understand where the commas are coming from now because we are within a template literal JavaScript knows that we want to display the array as a string of text so sort of automatically or behind the scenes it's almost as if JavaScript is calling the two string method that belongs to every array and this method creates a string by just smooshing the items of the array together and separating them with commas so if we want to remove the commas in between each object we need to be more proactive we need to acknowledge that our goal here is to return a string of text not an array so check this out right after pets data but still within the curly brackets let's say dot join in JavaScript every array has access to a method name join and it will generate a string of text based on the array and it will use whatever you give it as the separator so within these parentheses we could say quotes and then maybe a dash and that will output if you zoom in a string of text with dashes in between each item and you could use whatever you want as the separator so instead of a dash you could include a space and then the word pizza and then a space right you can do whatever you want however when your goal is to output HTML a nice little tip or trick is to just use nothing as your separator so just a quote and then not even a space just the closing quote cool so now we don't have any awkward separators between each item but the next issue that we need to fix is that each pet is being represented as just object object this is what javascript returns when it tries to display an object as a string of tag so to fix this it's almost as if we want an entirely new array right instead of an array of three objects with different properties ideally we would want an array with three strings of HTML text and luckily for us when you want to create or return a brand-new array based on another array well javascript has a tool that does exactly that and its name is Matt so check this out down within our array line of code right after pets data and right before the dot join let's say dot Matt in JavaScript every array has access to the map method and what does it do well it doesn't directly change or alter the original array instead it returns a brand new array and then we can run join on that new array just like we ran join on the original array right and that will return a nice string of text without any awkward separators okay so the question at hand is how does this map method work how does it create a new array well within these parentheses we give map a function and it will run that function once for each item in this original array and each time the function runs whatever it returns gets added to the brand a new array that its building so it's almost like running the original array through an assembly line so that we can modify each item in it it's hard to explain with words so let's just see it in action so within the map parentheses let's create an anonymous function so function parentheses curly brackets and within the curly brackets we can drop down just for readability and just for a quick test let's return the word hello so return quotes hello that will output hello hello hello but we don't want the items in our new array to just contain bogus text of hello instead we want bass our new array off our actual pet data so check this out within the parentheses of our anonymous function if we include a parameter so you can make up whatever name you want you could say unicorn or pizza or in this case I'm going to say pet because I think that makes sense but basically the map method is going to pass along the current item in the original array that it's looping through into your function so we can receive it with this parameter name and then we can use this name within the body of our function to access this original data however we please so for example instead of return quotes hello if we just say return pet that's going to give us the awkward familiar object object because the original items in our array are each an object however instead of returning the entire original object what if we do this we could just say pet dot name right because each object has a name property so this will output purrs loud barks a lot and meows a lot or we could say pet dot species and that will output cat dog cat but we don't want to just output one property of each animal if we look at the finished product we want to output an HTML div for each animal and then we can include all of the relevant data inside that div so back to our project check this out let's do this instead of just returning a property let's return a template literal so to backticks and in between the back ticks let's create a div let's give the opening div tag a class of animal and within this div let's add an image or a photograph of the animal just to stay organized and half traditional HTML indenting right after the opening back tick and before the div we could drop down to a new line and right before the closing back you could also drop down okay cool so now within this div drop down indent and let's include an image element so we want to give this a source and this value can just pull in the photo property that each one of our animal objects contains right this is a path to a jpg so down here for the source let's open up an expression so dollar sign curly brackets and then we can just say pet dot photo and just for styling and to control the size of the photograph on this image element let's also give it a class of pet - photo okay so all together this will output a div for each animal with a photo inside next let's add a headline with the pets name so right underneath this image element let's create a heading level two within it let's output the pet's name so dollar sign curly brackets to run an expression and we can just say pet dot name and how about right after that in parentheses we include whether it's a cat or a dog right so the species so these parentheses don't have anything to do with programming that's just how I want to display the species right so if we look at the finished product you can see the name of the animal and then in parentheses in a smaller font it says cat so back to our project let's just say dollar sign curly brackets Pet dot species and if we want this entire parentheses area to use a smaller font and a lighter color we can just wrap it in an HTML span close out the span here and let's give that span a class of species just for the CSS and why don't we also give the heading level to a class of pet - name okay and that will output this now all we have left is to output the age and the favorite Foods of each animal however before we get to that this highlighted part of our code is starting to look a bit messy it's spread out across eight lines it's got different methods and functions parentheses curly brackets a template literal it's just a little bit overwhelming to look at right so let me show you how we can clean this up a bit first let's cut or copy this section of code into our clipboard so begin selecting from the word return down to here and include the closing back tick okay so I'm going to cut that into my clipboard and then let's try to put this code back onto a single line and let's just give ourselves a clean slate and let's set the parentheses for math to be empty once again just like this now this is just my personal preference but I like my code to be set up so that each line only has one responsibility so this way you can look through your code and immediately know what's going on so let's set it up so that this line of code is responsible for calling map on this array and generating the new array and outputting it but we don't need to actually store the full HTML template within this line of code so instead check this out maybe up here right above the line that begins with document we can say function and let's just create a separate brand new function we can name it whatever we want I'm going to call it pet template parentheses curly brackets and within the body of the function here just paste in your clipboard okay and then down here on the line where we call math remember within these parentheses we give map a function so now we can just reference our brand new function so we can just say pet template now in order for these expressions to be able to actually access these properties we need to be sure that within the parentheses for this function definition here we include a parameter name now the name doesn't matter it could be anything but we've already coded this to you pet so within the parentheses you could say pet because remember the map method is going to pass along the current item in the array that it's looped to into this function so this way we are receiving that data and then we can use it so altogether this will output the exact same result only now our overall template is a little bit easier to read and you can even indent these three lines cool so we've got our header the actual content and our footer now let's finish building our pet template HTML to include the pets age and also list out their favorite foods in terms of displaying the age of the pet we actually need a bit of logic in place because if we look at our data all we have is a birth year so it's up to us to calculate the current year minus the birth year and output something that makes sense so if I look at the finished product and it take barks-a-lot as an example we don't just want to output the number that we calculate we want to make it human readable so we also want to add on text that says years old but if the animal is only one year old then we want to drop the s from the word years right one year old or if the animal was born in the current year we don't want to say 0 years old instead we could say something like baby so let me show you how we can implement all of that logic so back to our project into our code if we scroll down to our pet template function right underneath this heading level two line let's add a paragraph and let's say age colon and then for now I will just say blank but this is where it would say how many years old or baby before we set that up why don't we first make age and colon bold so we can wrap that in an HTML strong tag and this will output this ok now instead of the word blank let's actually work on that logic so I will delete blank and it's place create an expression so dollar sign curly brackets now I want to keep my HTML template clean and easy to read at a glance so instead of including all of our logic right here within the template why don't we do this within the curly brackets let's just call a function named age and this is not a magical reserved word in JavaScript there is no native function named age I just made that up and now we can create a helper function with this name so maybe right up here on a new line let's create a brand new function and we could name it whatever we want but let's call it age and for example within this function we could return the number 99 just as a quick example right so that would output age 99 for each pet so now instead of hard-coding this to 99 let's actually calculate the age so let's get rid of 99 and let's begin with the current year and then we can subtract the pets birth year from that so in JavaScript to get the current year you can just create a new instance of date this will give us a new date object and then we can look inside that object and say dot get full-year and this method will return a traditional four-digit year okay now once we have that we just want to subtract the birth year for the current pet now before we can do that we need to make sure that this function has access to that data so basically we want to pass the pets birth year as an argument so down here within our template when we call the age function within these parentheses let's say pet dot birth year right that's the name of the property that each one of our three pet objects contains okay and then within our age function within these parentheses let's just include a parameter the name doesn't matter but just to make sense I will call it birth year and now we can access and use that within the body of this function so get the full year and then tract birth year so altogether this will output 0 for pers loud 9 for barks-a-lot and five for meows a lot if you're watching this video in the future and the years no longer 2017 obviously your numbers will be different now at this point let's work on the logic so that if the age is zero we instead say baby and if the age is 1 we say year-old and if it's anything else we say plural years old so how would we set that up well back in our age function instead of returning this value right away let's delete return instead let's save it as a variable so we can make up a variable name I will say let calculated age equal and then our expression okay now right below this let's write an if statement so let's say if parentheses curly brackets within the parentheses let's say if calculated age equals 1 and only if that is the case then within these curly brackets we can say return a string of text that says one-year-old okay then right after the closing curly bracket for this if statement I will say else if parentheses curly brackets within these parentheses I will say if calculated age equals 0 only if that's the case then I will return a string of text that says baby and then finally after the closing curly bracket for this else if I will say else curly brackets if neither of these are true then let's just return a template literal so instead of quotes for a string let's use back ticks and say blank years old only instead of the word blank let's include an expression so dollar sign curly brackets and then we can just pull in our calculated age cool so altogether this will output baby if the age is 0 we see plural years-old here cool and if you wanted to test out the one-year-old scenario you could just adjust your JSON up at the very top here and just adjust the birth year for pers loud so for me I will set it back to 2016 and that way I can see that yes that works one-year-old no S on the year all right now changing gears let's work on our final task if we look at the finished product we see that the only thing left is the favorite foods feature so we've got a headline and then a bulleted list with their favorite foods and notice that some of the pets have favorite foods and some of them don't so this final task is going to put everything together and really test our abilities we're going to need conditional logic and we're going to need to loop through an array so jump back to our project and back in our code up at the top in our JavaScript you can see the first pet object has a property named fav foods which is an array right it contains three of their favorite foods barks-a-lot does not contain that property but the third pet meows a lot does so we need to update our pet template this function that returns a div with a class of animal let's update this to output favorite foods accordingly so underneath the paragraph that outputs their age let's include an expression so dollar sign curly brackets and in order to keep our template clean and easy to read at a glance instead of including that header and the bulleted list directly right here why don't we just call a function named foods and there is no native function in JavaScript named foods so now we need to create a function with that name so maybe right above our pet template function we could just say function foods parentheses curly brackets and you could imagine that we would return a template literal so back tick back and I'll drop down and let's return a heading level 4 that says they have ripped foods and then right below that we want a bulleted list of their foods right so unordered lists and within that we would have a list item for each of the foods so just as a hard coded test we could say food 1 and food - and just for CSS or design reasons let's give the unordered list a class of foods - list ok so all together that will give us something that looks like this now obviously we don't want to hard-code this to food 1 and food 2 but before we adjust this to pull in the real data let's first decide what we want to do if a pet object doesn't contain any favorite foods for example at the top of our JavaScript in our JSON data remember that barks-a-lot does not contain a favorite foods array now if that's the case not only are there no list items to show but we don't even want to display the heading level for favorite foods at all so it's almost as if down in our pet template right underneath the age text it's almost as if we only want to run the foods function if the current pet actually has a favorite foods property so our first instinct within this expression might be to try and write if parentheses curly brackets right and say only if pet dot fav foods only if that exists then run the foods function however this is not valid code we cannot do this because an if statement is just that it's a statement not an expression and within a template literal within dollar sign curly brackets you're only allowed to run something that's considered an expression a really oversimplified definition of an expression is just something that's expected to return a value instead of just doing something in general so let's delete that and instead let me show you something that's very very similar to an if statement but is allowed within a template literal we are going to use something called the ternary operator and the syntax might seem weird or unintuitive at first but hang in there with me so when you want to use a ternary operator it goes like this first you include a condition I'm just writing the word condition as a placeholder right but you could write anything that will evaluate to either true or false then you include a question mark and then you say what you want to do if the condition is true so just as a placeholder I will say yay then you include a colon and then you say what you want to do if the condition evaluates to false so just as a placeholder I say nay again I know the syntax looks a bit odd but it's a very compact and useful way of adding conditional logic to a template literal again this is called a ternary operator okay now let's fill in these placeholders so instead of the word condition here let's say pet dot babe foods and we don't need to check to see if it equals something we can literally just say pet dot fav foods and as long as it exists for the current pet object this will evaluate to true okay now if it is true instead of yay what do we actually want to do we want to call our foods function so just execute foods and what do we want to do if this evaluates to false if the current pet doesn't have any favorite foods let's just do literally nothing so you can just include a blank set of quotes with not even a space in between them altogether that will give us the favorite foods template for animals that have favorite foods and absolutely nothing will happen for animals that don't include that cool so now our absolute final task is just to pull in their actual favorite foods instead of food 1 and food 2 and we already have all of the tools needed to do that so back in our code within our ternary operator when we call the it's function let's pass it the actual favorite foods array as an argument so within these parentheses I will say pet dot fav foods okay and then up within our Foods function within these parentheses let's receive that data with the parameter the name here does not matter so I'm just gonna say foods and now I can use that within the body of the function so let's hollow out this unordered list so delete these fake list items and within the UL tags let's create an expression so dollar sign curly brackets within the brackets we can just say foods right and that alone will give us this and now you can see how this is coming full circle earlier in the lesson we already learned how to transform an array into the exact string of text that we want to generate so right now you can see there comma-separated wet food comma dry food comma any food so remember our trick to remove the commas every array in JavaScript has access to the join method and we can just use nothing or a completely empty pair of quotes as the separator so that will give us this and then if we want to transform each item in this array to include a bit of HTML around it well remember we learned about the map method which lets us generate a brand new array so check this out right after foods let's say dot map okay and remember we give math a function so within these parentheses let's include an anonymous function function parentheses curly brackets then the curly brackets you can drop down if you want to and let's return a template literals of two back ticks and let's create an HTML list item and within it we just want to pull it in the current item in the array or the current food so within the anonymous functions parentheses we need to include a parameter you could say whatever you want you could say item or you could say food okay and then we can use that parameter within the body of our function so within the list item let's include an expression and then just say food okay now altogether that will give us a bulleted list where each item in the array is a list item perfect but before we bring this lesson to a close I want to show you how we can use modern es6 flavor JavaScript to clean up that syntax a bit right because this chunk of code looks very messy it's hard to look at it and immediately know what's going on so let's clean it up a bit first let's convert this to use an es6 arrow function so within the parenthesis from map we can get rid of this word function here okay and then right after food and the closing parenthesis we can include an arrow symbol which is just equal sign greater than smooshed together okay next we don't really need to drop down to a new line here so let's put return on this same line so just get rid of this white space and the same thing goes here this could sit on the same line up above it so get rid of this white space and if your code sits on a single line you actually don't need the curly brackets surrounding the body of the function so I can also get rid of this opening curly bracket and this closing curly bracket and finally if you don't use curly brackets you don't need to explicitly include the word return it's just sort of implied so we can get rid of the word return cool and now our code is a lot cleaner now we can just scan through our project and when we see this line we can immediately know what's going on we're working with the foods array we're using map to generate a new version of the array this is the template for each new item in the array and then we're joining it together cool so just to prove that this code works if I save that and refresh we get the same desired result and you could actually take it one step further if you wanted to if you need to pass multiple parameters into your function you need to include parentheses around it like this so you could say food comma item comma pizza however many parameters you have however if you only have the one single parameter you don't need to wrap it in parenthesis so technically we could get rid of this opening and closing set of parentheses and if I save and refresh we get the same result and believe it or not that's going to bring this lesson to a close thank you so much for watching I hope you feel like you learned something and if you enjoyed this video you might also enjoy my premium courses I just launched a brand new one at the very end of October and it's a 25 hour course to help you become a wordpress developer now I know for a lot of you WordPress is a dirty disgusting word and you're immediately turned off but trust me this is a course about JavaScript as much as it is WordPress about a year ago WordPress finally added a REST API to its core what does this mean to you and I as JavaScript developers well it means that the platform that powers over 28% of the entire web yes WordPress is that popular it means that we can now control it with JavaScript instead of everything having to be done with PHP this brings WordPress into the 21st century and lets us flex our JavaScript muscles and build some really interactive features that are working with real WordPress data on the fly in real time if this sounds like something you're interested in and you want to check it out you can find a discounted coupon thing as well as links to all of my other courses in the description for this video thanks again for watching and stay tuned for more web development tutorials I'll see you next time and take care
Info
Channel: LearnWebCode
Views: 190,801
Rating: 4.9459352 out of 5
Keywords: javascript, template literals, es6, json
Id: DG4obitDvUA
Channel Id: undefined
Length: 39min 34sec (2374 seconds)
Published: Tue Dec 19 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.