在非 c# 文件中的 dotnet 新模板中添加可选内容

Oss*_*kin 7 c# dotnet-cli

我想根据开发人员在从模板创建 ac# 解决方案时选择的内容来修改 README.md 的内容。我该怎么做?

我知道你可以定义

"symbols": {
    "EnableContent":{
        "type": "parameter",
        "dataType":"bool",
        "defaultValue": "true"
    }
}
Run Code Online (Sandbox Code Playgroud)

template.config/template.jsondotnet 新模板中启用可选内容。

在 c# 代码中,您可以使用定义的符号来包含一些代码,如果EnableContent设置为 true(使用 c# 预处理器指令)

#if (EnableContent)
        public string foo()
        {
            return "bar";
        }

#endif
Run Code Online (Sandbox Code Playgroud)

在 .cshtml 中它可以像

@*#if (EnableContent)
<p>foobar</p>
#endif*@
Run Code Online (Sandbox Code Playgroud)

有什么方法可以在非 c# 文件中添加类似的决策,比如 Markdown 文件 (.md)?还是这取决于可用的 c# 预处理器指令?如果是这样,在使用 dotnet new 模板的上下文中,是否有任何解决方法可以在 Markdown 文件中使用 c# 预处理器指令。

附:我知道在这个例子中我可以做两个不同版本的 README.md 然后使用源修饰符选择正确的一个

"sources": [
    {
        "modifiers": [
            {
                "condition": "(EnableContent)",
                "exclude": [ "README1.md" ]
            },
            {
                "condition": "(!EnableContent)",
                "exclude": [ "README2.md" ]
            }
        ]
    }
Run Code Online (Sandbox Code Playgroud)

template.config/template.json但我的实际需要比这更复杂。

Oss*_*kin 14

我最终自己弄明白了这一点。有一种称为 SpecialCustomOperations 的方法来定义您自己的“语言”以启用任何文本文件中的可选内容。

这是一个记录不佳的功能,但我从这个答案中发现了在降价文件中启用 SpecialCustomOperations 的巨大价值。

template.config/template.json它是需要界定

"SpecialCustomOperations": {
  "**/*.md": {
    "operations": [
      {
        "type": "conditional",
        "configuration": {
          "if": ["---#if"],
          "else": ["---#else"],
          "elseif": ["---#elseif", "---#elif"],
          "endif": ["---#endif"],
          "trim" : "true",
          "wholeLine": "true",
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

然后下面的作品

---#if (FooBar)
Foo bar
---#elif (BarBaz)
Bar baz
---#else
Baz qux
---#endif
Run Code Online (Sandbox Code Playgroud)

另外,我发现可以对csproj文件(基本就是xml)定义类似的操作。在那里,您需要定义(在下面的例子这commnent

"SpecialCustomOperations": {
"**/*.xaml": {
  "operations": [
    {
      "type": "conditional",
      "configuration": {
        "actionableIf": [ "<!--#if" ],
        "actionableElse": [ "#else", "<!--#else" ],
        "actionableElseif": [ "#elseif", "<!--#elseif" ],
        "endif": [ "#endif", "<!--#endif" ],
        "trim" : "true",
        "wholeLine": "true",
      }
    }
  ]
}
}
Run Code Online (Sandbox Code Playgroud)

附:可以在此处找到默认启用特殊操作的文件类型列表。在其他文件类型中,需要手动定义 SpecialCustomOperations。