Search code examples
javascriptnode.jsalexa-skills-kitamazon-echo-show

Use display template to display random image


I am attempting to use the display templates to show a random image.

Right now the code below works for displaying one image, but if I add an additional line of code with a different image url source, it does not work.

Any ideas on what I could be doing wrong? Thanks so much!

function supportsDisplay() {
  var hasDisplay =
    this.event.context &&
    this.event.context.System &&
    this.event.context.System.device &&
    this.event.context.System.device.supportedInterfaces &&
    this.event.context.System.device.supportedInterfaces.Display

  return hasDisplay;
}

function renderTemplate (content) {

   switch(content.templateToken) {
       case "factBodyTemplate":
        
           var response = {
             "version": "1.0",
             "response": {

               "directives": [
                 {
                   "type": "Display.RenderTemplate",
                   "template": {
                     "type": "BodyTemplate7",
                     "title": content.bodyTemplateTitle,
                     "image": {
                        "contentDescription": "",
                        "sources": [
                          {
                            "url": "https://www.example.com/image.jpg",
                            "url": "https://www.example.com/image2.jpg",
                            "url": "https://www.example.com/image3.jpg"
                          }
                        ]
                      },
                    
                   }
                 }
               ],
             "sessionAttributes": content.sessionAttributes
           }
           this.context.succeed(response);
           break;
   }

}


Solution

  • EDIT:

    Okay, this might work... At the top of the post, add an array of your image sources, like so:

    const sourcesList = [
        "https://www.example.com/image.jpg",
        "https://www.example.com/image2.jpg",
        "https://www.example.com/image3.jpg"
    ]
    

    Then, where it asks you for a url over at images:

    "image": {
        "contentDescription": "",
        "sources": [
        {
            "url": sourcesList[Math.floor(Math.random() * sourcesList.length)],
    

    That should work. If it doesn't, try adding this at the bottom of your file: (no guarantee that this will work either)

    setInterval(function(){
        handlers['Get Fact']();
    ), 10000);//second value is the amount of time it takes to change image
    

    Did you include a file type with your new image?

    When you add an extra attribute to the JSON, make sure to add another comma after it. I.E.

    "url": "anotherURL.jpg",
    "url": "anotheranotherURL.jpg"
    

    Notice the comma at the end of line one.