Embedding Youtube Videos
Published on Mar 31, 2014
Ember.js saves you code. This is true even when you're doing something simple, like embedding youtube videos.
Hey, welcome back! It's been a crazy week so I'm going to give you a short and simple video today. We're going to add YouTube videos to our blog.
Here is the YouTube embed link they give you by default. Notice that it's in an iframe. This allows the player to choose between Flash and HTML 5 depending on your device. We definitely want that.
As our first step, we'll paste it into our HTML right here and then open up the index page to see if it works. Then you go to the post and uh-oh, it looks like it couldn't be found. That's because the link they give us, it's trying to find it on the file system. Let's edit it to call HTTP. We'll add HTTP before that and that should be enough to help it find it. Success!
Now we have a video loading in every post but it's the same video in every post so we're going to need to give each one its own unique video. In our post model, we're going to have an attribute called videoURL. Then, we'll put in the video URLs to our fixtures, and then we're going to bind the source attribute in our iframe. We'll use the bind-attr, which will hopefully be replaced soon in HTML bars, and the source will be bound to videoURL.
Now, we have the correct video and we have a different one in each. Those are the basics, but there are two tweaks I'd like to make. The first is that I don't want to have to include a video with every blog post. If I do one without a video, then it's just going to end up showing a big ugly box or nothing at all. In order to fix this, I'm going to go to my index and wrap the iframe in an if statement. If there is a videoURL, then we'll display it, so our blog posts without videos don't show them and our blog posts with videos do.
The second is that I don't want to display related videos at the end. I want people to click around my site instead, so I'm going to include the rel=0 attribute at the end of my URLs. However, adding it to the end of every URL will get onerous, especially once we get a lot of videos. Think if we have 100 videos, and then YouTube changes the API or we want to change the behavior. So, we're going to create a property called deckedOutVideoURL. It's going to get the videoURL and then add to it the properties that we want. We'll go into our HTML and change the source attribute and then when we play the video and go to the end, you'll see that there won't be any related videos, it'll just start over.
That is how to embed a YouTube video with Ember. I'll see you soon- happy coding!