跳至內容

建立自訂版面配置

版面配置是一種特殊類型的元件,Swagger UI 將其用作整個應用程式的根元件。您可以定義自訂版面配置,以便高度控制最終顯示在頁面上的內容。

預設情況下,Swagger UI 會使用內建於應用程式中的 BaseLayout。您可以透過將版面配置的名稱作為 layout 參數傳遞給 Swagger UI 來指定要使用的不同版面配置。請務必將您的自訂版面配置作為元件提供給 Swagger UI。


例如,如果您想要建立只顯示操作的自訂版面配置,您可以定義 OperationsLayout

1
import React from "react"
2
3
// Create the layout component
4
class OperationsLayout extends React.Component {
5
render() {
6
const {
7
getComponent
8
} = this.props
9
10
const Operations = getComponent("operations", true)
11
12
return (
13
<div className="swagger-ui">
14
<Operations />
15
</div>
16
)
17
}
18
}
19
20
// Create the plugin that provides our layout component
21
const OperationsLayoutPlugin = () => {
22
return {
23
components: {
24
OperationsLayout: OperationsLayout
25
}
26
}
27
}
28
29
// Provide the plugin to Swagger-UI, and select OperationsLayout
30
// as the layout for Swagger-UI
31
SwaggerUI({
32
url: "https://petstore.swagger.io/v2/swagger.json",
33
plugins: [ OperationsLayoutPlugin ],
34
layout: "OperationsLayout"
35
})

擴充預設版面配置

如果您想要圍繞 BaseLayout 進行建置,而不是取代它,您可以將 BaseLayout 拉入您的自訂版面配置並使用它

1
import React from "react"
2
3
// Create the layout component
4
class AugmentingLayout extends React.Component {
5
render() {
6
const {
7
getComponent
8
} = this.props
9
10
const BaseLayout = getComponent("BaseLayout", true)
11
12
return (
13
<div>
14
<div className="myCustomHeader">
15
<h1>I have a custom header above Swagger-UI!</h1>
16
</div>
17
<BaseLayout />
18
</div>
19
)
20
}
21
}
22
23
// Create the plugin that provides our layout component
24
const AugmentingLayoutPlugin = () => {
25
return {
26
components: {
27
AugmentingLayout: AugmentingLayout
28
}
29
}
30
}
31
32
// Provide the plugin to Swagger-UI, and select AugmentingLayout
33
// as the layout for Swagger-UI
34
SwaggerUI({
35
url: "https://petstore.swagger.io/v2/swagger.json",
36
plugins: [ AugmentingLayoutPlugin ],
37
layout: "AugmentingLayout"
38
})