Template::Plugin::XML::DOM(3) Plugin interface to XML::DOM

PRESENTING DOM NODES USING VIEWS

You can define a VIEW to present all or part of a DOM tree by automatically mapping elements onto templates. Consider a source document like the following:

    <report>
      <section title="Introduction">
        <p>
        Blah blah.
        <ul>
          <li>Item 1</li>
          <li>item 2</li>
        </ul>
        </p>
      </section>
      <section title="The Gory Details">
        ...
      </section>
    </report>

We can load it up via the XML::DOM plugin and fetch the node for the <report> element.

    [% USE dom = XML.DOM;
       doc = dom.parse(file = filename);
       report = doc.getElementsByTagName('report')
    %]

We can then define a VIEW as follows to present this document fragment in a particular way. The Template::Manual::Views documentation contains further details on the VIEW directive and various configuration options it supports.

    [% VIEW report_view notfound='xmlstring' %]
       # handler block for a <report>...</report> element
       [% BLOCK report %]
          [% item.content(view) %]
       [% END %]

       # handler block for a <section title="...">...</section> element
       [% BLOCK section %]
       <h1>[% item.title %]</h1>
       [% item.content(view) %]
       [% END %]

       # default template block converts item to string representation
       [% BLOCK xmlstring; item.toString; END %]

       # block to generate simple text
       [% BLOCK text; item; END %]
    [% END %]

Each BLOCK defined within the VIEW represents a presentation style for a particular element or elements. The current node is available via the 'item' variable. Elements that contain other content can generate it according to the current view by calling [% item.content(view) %]. Elements that don't have a specific template defined are mapped to the 'xmlstring' template via the 'notfound' parameter specified in the VIEW header. This replicates the node as an XML string, effectively allowing general XML/XHTML markup to be passed through unmodified.

To present the report node via the view, we simply call:

    [% report_view.print(report) %]

The output from the above example would look something like this:

    <h1>Introduction</h1>
    <p>
    Blah blah.
    <ul>
      <li>Item 1</li>
      <li>item 2</li>
    </ul>
    </p>

    <h1>The Gory Details</h1>
    ...

To print just the content of the report node (i.e. don't process the 'report' template for the report node), you can call:

    [% report.content(report_view) %]