カスタムレイアウトの作成

レイアウトは、Swagger UI がアプリケーション全体のルートコンポーネントとして使用する特殊な種類のコンポーネントです。ページに表示される内容を高度に制御するために、カスタムレイアウトを定義できます。

デフォルトでは、Swagger UI はアプリケーションに組み込まれているBaseLayoutを使用します。Swagger UI にレイアウトの名前をlayoutパラメーターとして渡すことで、使用するレイアウトを指定できます。カスタムレイアウトは、Swagger UI にコンポーネントとして提供してください。


たとえば、操作のみを表示するカスタムレイアウトを作成する場合は、OperationsLayoutを定義できます。

import React from "react"

// Create the layout component
class OperationsLayout extends React.Component {
  render() {
    const {
      getComponent
    } = this.props

    const Operations = getComponent("operations", true)

    return (
      <div className="swagger-ui">
        <Operations />
      </div>
    )
  }
}

// Create the plugin that provides our layout component
const OperationsLayoutPlugin = () => {
  return {
    components: {
      OperationsLayout: OperationsLayout
    }
  }
}

// Provide the plugin to Swagger-UI, and select OperationsLayout
// as the layout for Swagger-UI
SwaggerUI({
  url: "https://petstore.swagger.io/v2/swagger.json",
  plugins: [ OperationsLayoutPlugin ],
  layout: "OperationsLayout"
})

デフォルトレイアウトの拡張

BaseLayoutを置き換えるのではなく、BaseLayoutを基に構築したい場合は、カスタムレイアウトにBaseLayoutを取り込み、使用できます。

import React from "react"

// Create the layout component
class AugmentingLayout extends React.Component {
  render() {
    const {
      getComponent
    } = this.props

    const BaseLayout = getComponent("BaseLayout", true)

    return (
      <div>
        <div className="myCustomHeader">
          <h1>I have a custom header above Swagger-UI!</h1>
        </div>
        <BaseLayout />
      </div>
    )
  }
}

// Create the plugin that provides our layout component
const AugmentingLayoutPlugin = () => {
  return {
    components: {
      AugmentingLayout: AugmentingLayout
    }
  }
}

// Provide the plugin to Swagger-UI, and select AugmentingLayout
// as the layout for Swagger-UI
SwaggerUI({
  url: "https://petstore.swagger.io/v2/swagger.json",
  plugins: [ AugmentingLayoutPlugin ],
  layout: "AugmentingLayout"
})