visual-studio-code - 用户定义代码段中的 vscode if/else 条件

标签 visual-studio-code vscode-snippets

查看 vscode documentation for user defined snippets ,似乎使用正则表达式转换,您可以执行 if/else 条件。

但是,我似乎找不到这方面的任何示例,而且我正在努力理解仅基于 BNF 的正确语法。

谁能解释一下这个的语法?

例如,

假设我有这样一个片段:

"body": [
    "let color = '${1|white,black|}';",
    "let hex = '${???}';"
]

如果color==white,我希望十六进制输出#fff,否则如果是黑色#000

最佳答案

这个有效:

"color conditional": {
  "prefix": "_hex",
  "body": [

    "let color = '${1};",      
    "let hex = '${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}/}';" //works      
  ],
  "description": "conditional color"
},

但是,一旦我尝试使用默认占位符和选项,比如

"let color = '${1|white,black|}';",   // does not work

显然,您不能对默认占位符值进行片段转换。参见 transforms on placeholder values issues

我使用了更简单的 if 转换样式,所以这里:

${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}

如果有第 1 组 $[1} 在这种情况下 white 则用 #fff 替换第 1 组,如果第 2 组(black)替换为#000

你可以让它只是一个 if/else (white) 或者不是很容易。

"let hex = '${1/(white)/${1:?#fff:#000}/}';"  // any non-`white` entry will print `#000`.  

${1:? => 如果组 1 (white) 打印 #fff ,否则打印 #000

vscode 文档对这些条件替换不是很有帮助,如果您对它们的语法有更多疑问,请告诉我。

关于visual-studio-code - 用户定义代码段中的 vscode if/else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381007/

相关文章:

docker - 如何使刻度线显示为绿色?

visual-studio-code - 有没有办法在 vscode 片段前缀中使用正则表达式?

visual-studio-code - VSCode 项目片段在 Windows 上无法按预期工作

visual-studio-code - VS 代码片段将变量解释为字符串

ubuntu - Visual Studio Code 1.51.1 未在 Ubuntu 20.10 上启动(未找到错误 : GLIBC_2. 29')

editor - 在 Visual Studio Code 中设置语法突出显示的语言

git - 如何解决 VSCode GitHub pull 请求和问题扩展中的分支冲突?

c# - VS 代码 C# - System.NotSupportedException : No data is available for encoding 1252

visual-studio-code - 如何在 VSCode 中禁用代码片段的 Enter 按钮