📜 ⬆️ ⬇️

Layered menu in XSLT

Hello dear Habrovchane. I want to present a template for the output of a multi-level menu, although, altering it a bit, it will come down to display ordinary trees. I didn’t see anything similar on our favorite site, I didn’t look for it in the internet. For some, it may seem too easy, but I hope others will need it.

Here the topic of building trees has already been understood. In this example, another XML file structure and sharpening for other tasks.

Let's start with the XML file. The structure is not complicated. Each element consists of an identifier, a parent element identifier, a link, and a title.
')

menu.xml
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="menu.xsl"?> <root> <item id="1" idParent="0" link="#" title=" 1"/> <item id="2" idParent="1" link="#" title=" 2"/> <item id="3" idParent="1" link="#" title=" 3"/> <item id="4" idParent="2" link="#" title=" 4"/> <item id="5" idParent="2" link="#" title=" 5"/> <item id="6" idParent="1" link="#" title=" 6"/> <item id="7" idParent="6" link="#" title=" 7"/> <item id="8" idParent="6" link="#" title=" 8"/> <item id="9" idParent="0" link="#" title=" 9"/> </root> 

Without hesitation, we derive the transformation pattern

menu.xsl
 <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!--   --> <xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" doctype-system="about:legacy-compat"/> <!--   --> <xsl:template match="/"> <html lang="ru"> <head> <title> </title> </head> <body> <h1> </h1> <ul> <xsl:apply-templates select="/root/item[@idParent=0]"/> </ul> </body> </html> </xsl:template> <!--    --> <xsl:template match="/root/item"> <xsl:variable name="id" select="@id"/> <!--    --> <li> <a href="{@link}"> <xsl:value-of select="@title"/> </a> <!--    --> <xsl:if test="/root/item[@idParent=$id]"> <ul> <xsl:apply-templates select="/root/item[@idParent=$id]"/> </ul> </xsl:if> </li> </xsl:template> </xsl:stylesheet> 

The transformation template consists of two parts. The first one displays the main HTML tags and is not particularly interesting. One has only to pay attention to the template call, which starts calling elements with the parent identifier equal to zero.
The second part displays the menu item and checks if there are any elements with a parent identifier equal to the current identifier. If it is, it recursively calls the same template.

Naturally, items referring to non-existing parents will not be displayed.

Save the menu.xml and menu.xsl in the same folder and launch the first one in the browser. We see just such a picture.

Menu output
image

PS Thank you Dart for the errors found.

Source: https://habr.com/ru/post/138997/


All Articles