定制Swagger Codegen 3.0.50模板生成HTML API文档遇阻求助
解决Swagger Codegen 3.0.50 HTML文档定制问题
先处理你遇到的模板相关问题
1. 找不到modules/swagger-codegen/src/main/resources子文件夹
你下载的是预编译的Swagger Codegen稳定版(jar包或二进制程序),这类包本身不包含源码中的模板文件。要获取官方模板,需前往GitHub的Swagger Codegen仓库切换到3.0.50版本标签,找到modules/swagger-codegen/src/main/resources/htmlDocs目录下的所有模板文件,复制到本地自定义模板文件夹后再修改。
2. -t参数传入自定义模板未被识别
HTML文档生成器要求自定义模板文件夹的结构与官方模板一致:
- 先创建本地文件夹(比如
custom-html-templates) - 在该文件夹内新建
htmlDocs子目录,将修改后的模板文件全部放入这个子目录 - 执行生成命令时,
-t参数指向包含htmlDocs的父文件夹,而非直接指向htmlDocs
示例完整命令:
java -jar swagger-codegen-cli-3.0.50.jar generate -i your-api-spec.yaml -l html -o ./generated-docs -t ./custom-html-templates
再实现你的三个定制需求
1. 仅保留Curl和Python示例
找到htmlDocs下的sample.mustache模板(渲染请求示例的核心文件),修改循环逻辑,只保留type为curl和python的示例:
{{#samples}} {{#if (or (equal type "curl") (equal type "python"))}} <div class="tab-pane" id="{{id}}"> <!-- 原有的示例渲染代码 --> </div> {{/if}} {{/samples}}
2. 替换Python示例为requests库代码
打开htmlDocs下的sample_python.mustache,完全替换原有基于swagger_client的代码为requests实现:
- GET请求示例:
import requests url = "{{basePath}}{{path}}" headers = { '{{#firstHeader}}{{headerName}}{{/firstHeader}}': '{{#firstHeader}}{{headerValue}}{{/firstHeader}}', } params = { {{#queryParams}} '{{paramName}}': '{{exampleValue}}', {{/queryParams}} } response = requests.get(url, headers=headers, params=params) print(response.status_code) print(response.json())
- POST请求示例:
import requests import json url = "{{basePath}}{{path}}" headers = { 'Content-Type': 'application/json', '{{#firstHeader}}{{headerName}}{{/firstHeader}}': '{{#firstHeader}}{{headerValue}}{{/firstHeader}}', } payload = json.dumps({ {{#bodyParams}} '{{paramName}}': '{{exampleValue}}', {{/bodyParams}} }) response = requests.post(url, headers=headers, data=payload) print(response.status_code) print(response.json())
模板中的basePath、path、queryParams等变量会由Swagger Codegen自动填充对应值。
3. 为GET、POST生成不同模板
在sample_python.mustache中通过method变量做分支判断,渲染不同代码:
{{#equal method "GET"}} <!-- 上述GET请求代码 --> {{/equal}} {{#equal method "POST"}} <!-- 上述POST请求代码 --> {{/equal}}
如果想拆分模板文件,可创建sample_python_get.mustache和sample_python_post.mustache,再在sample.mustache中根据方法引入对应子模板:
{{#samples}} {{#equal type "python"}} {{#equal method "GET"}} {{> sample_python_get}} {{/equal}} {{#equal method "POST"}} {{> sample_python_post}} {{/equal}} {{/equal}} {{/samples}}
内容的提问来源于stack exchange,提问作者FraDV
相关产品推荐
相关产品推荐

