Using xsl:call-template - Exercise

Contact Us or call 1-877-932-8228
Using xsl:call-template - Exercise

Using xsl:call-template

Duration: 10 to 15 minutes.

In this exercise, you will practice passing parameters to named templates.

  1. Open TemplatesParametersVariables/Exercises/CourseAsList.xsl.
  2. Below the first template, which matches the root, create a new template name StartHTML.
  3. Move the entire contents of the first template into the new template you just created.
  4. Add an xsl:call-template element to the first template that calls the StartHTML template and passes it the value of the title element from the source XML document.
  5. Modify the StartHTML template so that it accepts the passed-in parameter and uses it in the nested HTML title and h1 elements.
  6. To test your solution, transform TemplatesParametersVariables/Exercises/XML101.xml against TemplatesParametersVariables/Exercises/CourseAsList.xsl.

Solution:

TemplatesParametersVariables/Solutions/CourseAsList.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
	<xsl:call-template name="StartHTML">
		<xsl:with-param  name="Title" select="course/head/title"/>
	</xsl:call-template>
</xsl:template>

<xsl:template name="StartHTML">
	<xsl:param name="Title" select="'Untitled'"/>
	<html>
		<head>
			<title><xsl:value-of select="$Title"/></title>
			<style type="text/css">
				#outline { font-size:larger }
				ul ul {font-size: smaller }
			</style>
		</head>
		<body>
		<h1><xsl:value-of select="$Title"/></h1>
		<div id="courseNum">
			<xsl:value-of select="/course/head/course_num"/>
		</div>
		<div id="courseLength">
			<xsl:value-of select="/course/head/course_length"/>
		</div>
		<xsl:apply-templates select="/course/body/prerequisites"/>
		<xsl:apply-templates select="/course/body/outline"/>
		</body>
	</html>
</xsl:template>

<xsl:template match="prerequisites">
	<h2>Prerequisites</h2>
	<ul>
	<xsl:for-each select="prereq">
		<li>
			<xsl:value-of select="." />
			<xsl:if test="@optional = 'true'">
				(optional, but recommended)
			</xsl:if>
		</li>
	</xsl:for-each>
	</ul>
</xsl:template>

<xsl:template match="outline">
	<h2>Course Outline</h2>
	<div id="outline">
		<xsl:apply-templates />
	</div>
</xsl:template>

<xsl:template match="topics">
	<ul>
		<xsl:apply-templates />
	</ul>
</xsl:template>

<xsl:template match="title">
	<li><xsl:apply-templates /></li>
</xsl:template>

</xsl:stylesheet>
Next