XQuery/Dynamic Module Loading

Motivation
You want to conditionally import a module. For example the module might provide a list of all the functions to style a web page such as header/footer and breadcrumbs.

Module import
We will use the XQuery function util:import-module. This function has three arguments:


 * $namespace: The full URI of the module that you are loading such as  http://example.com/my-module 
 * $prefix: the prefix you want to use to reference each function in the module such as style
 * $location: the database path that you will be loading the module from such as an absolute path/db/modules/my-module.xqm or a relative path my-module.xqm

For example the following will import a module called my-module from the /db/modules collection.:

util:import-module(xs:anyURI('http://example.com/my-module'), 'style', xs:anyURI('/db/modules/my-module.xqm'))

The function xs:anyURI is used to cast each string into the URL type.

Function invocation
Because the namespace is declare dynamically, the imported functions have to be invoked using util:eval. The input to this function is a string containing an XQuery expression. e.g.

util:eval('style:header')

Example
The following will randomly load one of two style modules.

Run

Style A Module
Here is an example of a style module. It has four functions. One to import the CSS files, one for the header, one for the navigation breadcrumb and one for the footer.