Kroc/DOMTemplate

How to address root element of a template?

Closed this issue · 3 comments

I cannot find the right way to address the root element of a given template.

$template = <<<HTML
<nav id="menu">
    <a href=""></a>
</nav>
HTML;

$menu = new DOMTemplate($template);

$menu->addClass('#menu', 'main');
$menu->setValue('#menu/a@href', '/');

echo $menu;

In example above both calls do nothing. If I remove “#menu/” from setValue call only then the href gets set.

It seems there’s no obvious way to address root element and if it’s present in the query nothing is found.

Kroc commented

This is an XPath thing, use a leading / to select the root element, so either / or /nav. In the future the CSS :root selector will be supported

Thanks, I’ve figured it out!

For my example above to add a class it should be addressed as /* and to set its attributes /*/@attr-name.

$menu->addClass('/*', 'main');
$menu->setValue('/*/@attr-name', 'value');
Kroc commented

Alas, CSS is just an illusion; what's really happening under the hood is XPath and the shorthand I created was the barest minimum of "CSS-like" syntax to support my particular use case. I began work on a true CSS to XPath translator (https://github.com/Kroc/css2xpath) but that's quite an undertaking. I will likely use an existing solution (there are multiple) until I can complete my own (I have discovered that the approach that others have taken is likely inaccurate)