Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code snippets: if/else conditions syntax

Looking at the vscode documentation for user defined snippets, it would appear that using the regex transform, you can do if/else conditions.

However, I can't seem to find any examples of this and I'm struggling to understand the correct syntax based on the BNF alone.

Can someone explain the syntax for this?

For example,

Lets say I have a snippet like this:

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

If color==white, I want hex to output #fff, otherwise if black #000.

like image 843
NSjonas Avatar asked Jun 17 '26 04:06

NSjonas


1 Answers

This works:

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

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

However, as soon as I try it with default placeholders and choices, like

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

Apparently, you cannot do snippet transforms on default placeholder values. See transforms on placeholder values issues

I used the simpler if transform style, so here:

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

if there is a group 1 $[1} in this case white then replace that group 1 with #fff and if group 2 (black) replace with #000, etc.

You could make it just an if/else (white) or not pretty easily.

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

${1:? => if group 1 (white) print #fff , else print #000

The vscode docs are not very helpful on these conditional replacements, if you have more questions on their syntax, let me know.

like image 117
Mark Avatar answered Jun 19 '26 17:06

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!