XQuery/動態模組載入
外觀
< XQuery
您想要有條件地匯入模組。例如,該模組可能會提供一個包含所有用於為網頁設定樣式的函式的列表,例如標題/頁尾和麵包屑導航。
我們將使用 XQuery 函式 util:import-module()。此函式具有三個引數
- $namespace: 您要載入的模組的完整 URI,例如 http://example.com/my-module
- $prefix: 您想要用於引用模組中每個函式的字首,例如 style
- $location: 您將從中載入模組的資料庫路徑,例如絕對路徑 /db/modules/my-module.xqm 或相對路徑 my-module.xqm
例如,以下將從 /db/modules 集合匯入名為 my-module 的模組。
util:import-module(xs:anyURI('http://example.com/my-module'), 'style', xs:anyURI('/db/modules/my-module.xqm'))
函式 xs:anyURI 用於將每個字串強制轉換為 URL 型別。
由於名稱空間是動態宣告的,因此必須使用 util:eval 呼叫匯入的函式。此函式的輸入是一個包含 XQuery 表示式的字串。例如:
util:eval('style:header()')
以下將隨機載入兩個樣式模組中的一個。
xquery version "1.0";
declare option exist:serialize "method=xhtml media-type=text/html omit-xml-declaration=yes indent=yes";
let $module := if (math:random() < 0.5)
then
util:import-module(
xs:anyURI('http://example.com/style-a'),
'style',
xs:anyURI('style-a.xqm')
)
else
util:import-module(
xs:anyURI('http://example.com/style-b'),
'style',
xs:anyURI('style-b.xqm')
)
return
<html>
<head>
<title>Test of Dynamic Module Import</title>
{util:eval('style:import-css()')}
</head>
<body>
{util:eval('style:header()')}
{util:eval('style:breadcrumb()')}
<h1>Test of Dynamic Module Import</h1>
{util:eval('style:footer()')}
</body>
</html>
這是一個樣式模組的示例。它具有四個函式。一個用於匯入 CSS 檔案,一個用於標題,一個用於導航麵包屑,一個用於頁尾。
xquery version "1.0";
module namespace style='http://example.com/style-a';
declare function style:import-css() {
<link type="text/css" rel="stylesheet" href="style-a.css"/>
};
declare function style:header() {
<div class="header">
<h1>Header for Style A</h1>
</div>
};
declare function style:breadcrumb() {
<div class="breadcrumb">
<h1>Breadcrumb for Style A</h1>
</div>
};
declare function style:footer() {
<div class="footer">
<h1>Footer for Style A</h1>
</div>
};
body {
color: blue;
}
xquery version "1.0";
module namespace style='http://example.com/style-b';
declare function style:import-css() {
<link type="text/css" rel="stylesheet" href="style-b.css"/>
};
declare function style:header() {
<div class="header">
<h1>Header for Style B</h1>
</div>
};
declare function style:breadcrumb() {
<div class="breadcrumb">
<h1>Breadcrumb for Style B</h1>
</div>
};
declare function style:footer() {
<div class="footer">
<h1>Footer for Style B</h1>
</div>
};
body {
color: red;
}