We have accomplished the following so far.
Created a YouTube component that will add a specific YouTube video to the page.
Created a dialog where the author can enter a different URL.
The requirement was to update the video using the URL entered by the author.
Let us start. We will create a JavaScript file named url.js to write our logic.
- Create a js file url.js.
- Copy and paste the following code:
use(function () {
var CONST = {
PROP_TITLE: "jcr:title",}
var url = {};
// The url entered in the dialog
url.text = granite.resource.properties[CONST.PROP_TITLE]
if (url.text ==null)
{
url.text = "https://www.youtube.com/embed/dI1yi2mmNuo";
}
// Adding the constants to the exposed API
url.CONST = CONST;
return url;
});
Let us go through the code line-by-line. It creates a JavaScript function. It creates a constant PROP_TITLE and assigns jcr:title to it. It is a very important property. Let us take a look at the JCR properties after you add a value to the component’s dialog.
Go to content > aem-company > jcr: content > content > youtube_1.
Note that jcr:title property captures the URL entered in the dialog. We have entered the name of the dialog as ./title and that’s the reason its value is captured as jcr:title. The code creates a variable url. Added a text property to the URL and it captures granite.resource.properties[CONST.PROP_TITLE], basically the URL entered by the authors. Then the code checks if the url.text property is null. It’s null when there is no value entered in the dialog. In that case, we are assigning a default value. We are returning url as a constant.
Now let us change the code that we wrote in the YouTube.html to use the script. Copy and paste the following code to YouTube.html.
<div data-sly-use.url="url.js" style="overflow: hidden;">
<iframe width="600" height="510" src="${url.text}" frameborder="0" allowfullscreen></iframe>
</div>
The data-sly-use attribute assigns the return value of url.js to the url variable. We extract the url from the url property using ${url.text}. See how simple it is.
Now let me give you another URL to test: https://www.youtube.com/embed/kl3Hz-4x4L0 (This is another YouTube video that I shared some time back. It has a title, AEM Authors, Templates, Components.)
- Drag and drop the YouTube component to the web page.
- Select it and select Edit.
- Enter the URL that I gave above.
- Select OK.
There are lots of pitfalls in the component. In the first place, it does not check if the entered string is a URL or not. Also, no need to display a video in the first instance, and so on. The intention was to show you how to capture user input from the dialog, and we have succeeded.
See you in the next session.
No comments:
Post a Comment
If you have any doubts or questions, please let us know.