如何在dotnet new模板中处理参数首字母大小写及使用forms
在.NET New模板中处理变量首字母大小写及Forms的使用方法
一、使用Forms处理首字母大小写(优先方案)
Forms是.NET模板引擎官方提供的参数转换方案,支持firstLowerCase和firstUpperCase这类首字母转换规则,配置和使用步骤如下:
- 在template.json中定义Form规则
在模板配置文件的根节点下添加forms字段,针对rootEntity参数定义首字母转换规则:
{ "$schema": "http://json.schemastore.org/template", "author": "Your Name", "name": "Your Template", // 其他模板配置项... "forms": { "rootEntityLowerFirst": { "identifier": "firstLowerCase", "parameters": { "source": "rootEntity" } }, "rootEntityUpperFirst": { "identifier": "firstUpperCase", "parameters": { "source": "rootEntity" } } }, "parameters": { "rootEntity": { "type": "string", "defaultValue": "Notebook", "description": "The root entity name" } } }
identifier: 指定转换器类型,firstLowerCase负责将首字母转为小写(其余字符保持原样),firstUpperCase负责将首字母转为大写。source: 指向要转换的原参数,即你定义的rootEntity。
- 在模板文件中引用Form
在需要替换为小写首字母的位置,直接使用定义好的Form名称:
// 示例:生成首字母小写的变量名 private readonly I{{rootEntity}}Repository _{{rootEntityLowerFirst}}Repository;
若用户输入rootEntity为Notebook,这段代码会被替换为:
private readonly INotebookRepository _notebookRepository;
需要首字母大写的场景,直接使用原参数{{rootEntity}}或定义好的rootEntityUpperFirst即可。
二、直接修改变量首字母大小写(非优先方案)
如果暂时不想使用Forms,也可以通过字符串截取+大小写转换的组合方式实现,但写法相对繁琐:
- 首字母转小写:
{{rootEntity | substring 0 1 | casing lower}}{{rootEntity | substring 1}} - 首字母转大写:
{{rootEntity | substring 0 1 | casing upper}}{{rootEntity | substring 1}}
比如输入rootEntity为notebook,首字母转大写的写法会输出Notebook。
内容的提问来源于stack exchange,提问作者Vaccano
相关产品推荐
相关产品推荐

