How can I modularize a repeated set of outputs in an xslt transform? For example I have something like the following (pseudo code).
<foreach "path">
<if "count(/subPath) = 0">
<a><value-of "x"/></a>
<b><value-of "y"/></b>
<c></c>
</fi>
<else>
<foreach "subPath">
<a><value-of "../x"/></a>
<b><value-of "../y"/></b>
<c><value-of "z"/></c>
</foreach>
</else>
</foreach>
and would like something like the following
<foreach "path">
<if "count(/subPath) = 0">
<?/>
</fi>
<else>
<foreach "subPath">
<?/>
</foreach>
</else>
</foreach>
<?>
<a><value-of "../x"/></a>
<b><value-of "../y"/></b>
<c><value-of "z"/></c>
</?>
What construct am I looking for?
I. Pseudo-code translation
Your pseudocode translates 1:1 to this XSLT transformation:
when applied on this XML document (no such document is provided in the question!!!):
the wanted, correct result is produced:
II. Refactoring:
This is a refactored, equivalent transformation that doesn’t use any
xsl:for-eachor any explicit conditional instructions:when applied on the same XML document (above), again the same correct result is produced:
Do note:
Templates/pattern matching to avoid using explicit conditional instructions. This is the most powerful, XSLT-specific design pattern.
There is no duplicate code.
Each templates matches exactly the node it has to process, under the exact required conditions.
The code of the first template is re-used by also giving it a name, so that it can be explicitly called. In this way code duplication is avoided.