如何在ApiPlatform中隐藏Swagger的所有Schemas区块?
解决ApiPlatform Swagger隐藏Schemas区块的几种思路
不用去改vendor里的Twig文件,给你几个更靠谱的方案:
方案一:前端自定义JS隐藏(最快实现)
Symfony允许你覆盖第三方Bundle的模板,不用碰vendor目录:
- 在你的项目里创建模板文件:
templates/bundles/ApiPlatformBundle/SwaggerUi/index.html.twig - 把默认模板的内容复制过来(可从
vendor/api-platform/core/src/Symfony/Bundle/Resources/views/SwaggerUi/index.html.twig里复制) - 在模板末尾的JS初始化代码后,添加一段自定义脚本,等Swagger UI渲染完成后隐藏Schemas区块:
window.addEventListener('load', function() { const ui = window.ui; if (!ui) return; // 监听Swagger UI加载完成事件 ui.on('ready', function() { // 隐藏Schemas主区块 const schemasContainer = document.querySelector('.models-container'); if (schemasContainer) schemasContainer.style.display = 'none'; // 隐藏侧边栏的Schemas入口链接 const schemasLink = document.querySelector('.swagger-ui .models a'); if (schemasLink) schemasLink.style.display = 'none'; }); });
这个方法不用改后端逻辑,纯前端操作,缺点是用户如果直接查看OpenAPI JSON文档,Schemas还是存在的。
方案二:后端移除OpenAPI文档中的Schemas(彻底解决)
如果想让Schemas从根源上消失,直接修改ApiPlatform生成的OpenAPI文档:
- 创建一个事件订阅器类:
// src/EventListener/HideSchemasListener.php namespace App\EventListener; use ApiPlatform\Core\Event\Event\DocumentationEvent; class HideSchemasListener { public function __invoke(DocumentationEvent $event): void { $docs = $event->getDocumentation(); // 移除components下的schemas节点 if (isset($docs['components']['schemas'])) { unset($docs['components']['schemas']); $event->setDocumentation($docs); } } }
- 在
config/services.yaml里注册这个订阅器,注意优先级要低于默认的文档生成器:
services: App\EventListener\HideSchemasListener: tags: - { name: kernel.event_listener, event: api_platform.documentation, priority: -10 }
这样生成的OpenAPI文档里就完全没有Schemas部分了,Swagger UI自然不会渲染它。
方案三:自定义CSS快速隐藏(最简便)
如果只是临时隐藏,不想写JS或PHP,可以直接在ApiPlatform配置里加自定义CSS:
在config/packages/api_platform.yaml里添加:
api_platform: swagger_ui: extra_config: customCss: | .models-container { display: none !important; } .swagger-ui .models a { display: none !important; }
这个方法最省事,但可能会有页面加载时的闪烁,因为CSS是在DOM渲染后生效的。
内容的提问来源于stack exchange,提问作者Andrey Bolonin
相关产品推荐
相关产品推荐

