Kroc/DOMTemplate

New methods for inserting content

nkrs opened this issue · 1 comments

nkrs commented

Since there are methods for setting the element content, I thought adding methods for appending and prepending content to nodes would be good. I've made a hack a while ago (https://gist.github.com/1677955) to add these as I needed them for my own needs, but there were several changes in the API since then and my edits became incompatible.

A simple use case for this could be a simple <details> widget:

<details>
  <summary>Table of Contents</summary>
</details>

where using the the set method on the details element would completely replace its contents with new nodes. This is where using append would make sense because it would add whatever content at the end of the parent node. Similarly, prepend would add content at the beginning.

Edit: implementing insertBefore and insertAfter as well would give more control to positioning content where it is needed in the markup, without having too many parent elements to set the inner contents to.

Kroc commented

This is slightly out the scope of DOMTemplate at the moment, but I can see a place for it. I’ll give it my consideration.

The first version of DOMTemplate worked by extending the PHP DOM classes—DOMElement, DOMNode &c.—but this fell apart when it got to queries because it is not yet possible to extend DOMNodeList and a query always returns a DOMNodeList so I couldn’t make my methods automagically apply to multiple query results.

That's why the current API is the way it is, it’s quite odd when you look at it, but ultimately I think it works better than before because it’s no longer as long winded.

The nature of DOMTemplate is to have all your HTML present, and remove what is not necessary, rather than programatically add content. If you add too much then your template becomes tangled with the logic and you’re right back to templating square one! Use repeat if you need to add stuff!

You should simply sub-class DOMNode and add your insertBefore and insertAfter functions there. This is common behaviour for anybody working with the DOM. Remember that DOMTemplate->query will give you a regular PHP DOMNode you can manipulate.

tl;dr remove, don’t add, when using DOMTemplate; extend DOMNode to use insertBefore / insertAfter