tvostvml

TVML Add items dynamically?


I have seen this question (Force view to reload tvml content on Apple TV/tvos) and the answer describes how you could remove things from the DOM but is there any way to add them?

I know about the standard appendChild on a NodeList but how would you create the proper element to be appended? That is, when you create a document in TVML it is a special XML syntax that is then parsed into a document. Is there a way to parse just a portion of a document so that you can then add it into, say a section within a shelf to dynamically add more items to the row after the document has been presented?

P.S. I've tried using Presenter.parser.parseFromString() with the xml for the new item but it is throwing a IKDOMException with that syntax.


Solution

  • There are many approaches you can take to accomplish adding items dynamically. An important thing to note is that Apple's sample code is NOT structured for dynamic data very well.

    After you create a template, you can change the document in a variety of ways. You should have ownership of the document after the template is created. In the following example, the variable doc contains a Stack Template document I'd like to manipulate.

      var shelves = doc.getElementsByTagName("shelf"); //get all the shelves
      var shelfToAddTo = shelves.item(0); //choose the index for the shelf you want to add to.
      var sectionToAdd = `<section>
                <lockup>
                <img src="pathToImg" width="100" height="100"/>
                <title>Title Goes Here</title>
                </lockup> 
                </section>`;
      shelfToAddTo.insertAdjacentHTML('beforeend', sectionToAdd); //this will add the new section before the </shelf> tag.
    

    This will add a new section and lockup to the first shelf in your document.