I wanted to express my excitement about plainTemplates today.

The plainTemplates approach for template generation is to have the template be plain HTML, and then to have a PHP processor fill certain parts of the document with dynamic content. It's familiar territory for anyone who has written an AJA[X?] application in recent times.

It makes a lot of sense for anyone who is used to adding javascript entirely at the head of a page instead of by adding javascript throughout the HTML, and I suspect that, properly implemented, it could not only save time, but increase the hardiness of web applications.

The DOM, XHTML, and XPath were all developed to enable us to treat (X)HTML as a structured document, and not just markup on a bunch of text. But, templates - like so many other things - are stuck in the mindset that the output we send to our browsers is nothing but a long string of text that we must assemble as such.

This mindset is one of the root causes of why XSS, as a family of security vulnerabilities, exist. We are inserting content into a page by inserting characters at some offset of a string: without context. Without knowing the context of where we are adding data -- which node in the XML/HTML DOM we're modifying, and what our modification is (are we modifying a node? Adding a node? Adding several nodes?) we have no hope of building tools that are aware of exceptions.

We should never edit content without being aware of the context. In some sense, this is nothing radical - we don't worry about a ' in the context of XML data, but we do worry about it in the context of SQL commands.

For SQL injection, we've mitigated the problem by escaping data so that it does not break out of its context but we've solved the problem by using (real or emulated) prepared statements -- programming directives that inform the database layer of what is our content is and what the context is in which we are using it.

For XSS, we're all building applications that defend against it by escaping, but rarely do we use the XHTML equivalent of prepared statements. A few weeks ago, I was playing with PHP's SimpleXML as a way of manipulating XHTML by adding data here and there (in my case, I was using it to prepopulate forms). I wasn't setting an attribute on an element by adding a string to the middle of a string that looked like "<input ....>", I was setting an attribute with setAttribute(). To me, this is context.

plainTemplates and phpQuery both are suited to take this to the next level - making the norm for templating being 'add this to these nodes.' But just as how the DOM lets us 'cheat' with innerHTML and other contextless vectors to edit arbitrary content, we must build a templating system that is aware of the DOM, and the changes it makes to it.