Reputation: 6422
I have a problem.
I have an XML file that contains information about 100 courses.
I have an XSL file that nicely displays the list of 100 courses.
But what if I want to only display 1 course. Can I pass a parameter to the XSLT file to tell it to only display "ENGL 100" ?
The XML looks something like this:
<document>
<menu>
<item>
<name>MTH 300</name>
<brief>Mathematics Skill Development</brief>
<description>A course in the fundamentals of ...</description>
</item>
<item>
<name>MTH 301</name>
<brief>Basic Algebra</brief>
<description>An introduction to algebra, ...</description>
</item>
...
I know I could write an XSLT file called "eng100.xsl" to loop through the XML and display only ENG 100 but I don't want to have to write dozens of these files.
The XML is dynamic and I am able to control it. I want the XSLT file to be static and never change.
Is there any way to pass parameters into the XSLT?
Upvotes: 7
Views: 21223
Reputation: 6201
Very old question I know -but just in case it helps somebody. If you are using any server-side scripting engine - consider using HTTP Params: you can link to the XSL like this (assuming a PHP backend here)
<?xml-stylesheet href="myxsl.xsl.php?my_param=abc" type="text/xsl"?>
Note the renamed file to '[...].xsl.php' - and we'll need to set 'content-type' back to 'xml' as well:
The contents of the XSL can then be mixed with a small amount of server-side code to set up an XSL variable. For example:
<?php header('Content-Type: application/xml; charset=utf-8'); ?>
[...]
<xsl:variable name="my_param"><?=$_GET[my_param']?></xsl:variable>
Upvotes: 0
Reputation: 57777
You can pass parameters to XSLT, how this is done depends on your XSLT processor, but usually as additional command arguments, if it's a command-line processor.
You declare parameters using
<xsl:param name="courseName" select"initialValue"/>
You can then test this parameter in your XSLT, and invoke a different template depending on it's value. For example, if the parameter is empty, then invoke the current template that processes all elements, otherwise invoke a template that only processes elements when the item name equals the parameter value. You can do this with a test
<xsl:template match="item">
<xsl:if test="$courseName=name(./name)">
<xsl:call-template name="yourOriginalTemplate"/>
</xsl:if>
</xsl:template>
But by filtering and formatting, you are mixing two concerns in one file. I would separate out the selection of the XML elements from formatting - have two xslt files for that and run them as a pipeline.
Upvotes: 9