WebStorm 2021.1 Help

Live template variables

When you expand a live template abbreviation, its variables either appear as input fields where you can type values or are replaced with values. These may be default values that you can modify or values calculated using functions.

To declare variables within templates, use the following format: $VAR$.

In expressions, use variable names without opening and closing dollar characters $, for example, lowercaseAndDash(ComponentName).

Define each variable using an expression and provide a default value for cases when the expression fails to evaluate.

This expression may contain the following constructs:

  • String constants in double quotes

  • Names of other variables defined in a live template

  • Predefined functions with possible arguments

Configure template variables

  1. In the Settings/Preferences dialog Ctrl+Alt+S, go to Editor | Live Templates.

  2. Select a template where you want to configure variables.

  3. Specify variables in the template text and click Edit variables.

  4. In the Edit Template Variables dialog, you can do the following for each variable:

    • Change the variable name

    • Define an expression using predefined functions

    • Specify the default value for cases when the expression fails to evaluate

    • Specify whether you want to skip the variable when prompting the user for input if the expression evaluated successfully

Predefined template variables

WebStorm supports the following predefined live template variables that cannot be modified:

  • $END$ indicates the position of the cursor when the code snippet is complete, and you can no longer press Tab to jump to the next variable.

  • $SELECTION$ is used in surround templates and denotes the code fragment to be wrapped. After the template expands, it wraps the selected text as specified in the template. For example, if you select EXAMPLE in your code and invoke the "$SELECTION$" template via the assigned abbreviation or by pressing Ctrl+Alt+T and selecting the desired template from the list, WebStorm will wrap the selection in double quotes as follows: "EXAMPLE".

Functions used in live template variables

The following functions can be used to define live template variables:

FunctionDescription
blockCommentEnd()

Returns the characters that indicate the end of a block comment in the current language context.

blockCommentStart()

Returns the characters that indicate the start of a block comment in the current language context.

camelCase(<String>)

Converts a string into camelCase.

For example, camelCase("my-text-file"), camelCase("my text file"), and camelCase("my_text_file") all return myTextFile.

capitalize(<String>)

Capitalizes the first letter of a string.

For example, capitalize("name") returns Name. Or you can combine it into capitalize(camelCase("my awesome class")) to get MyAwesomeClass.

capitalizeAndUnderscore(<String>)

Capitalizes all the letters of a string, and inserts an underscore between the parts.

For example, capitalizeAndUnderscore("FooBar"), capitalizeAndUnderscore("foo bar"), and capitalizeAndUnderscore("foo-bar") all return FOO_BAR.

clipboard()Returns the contents of the system clipboard.
commentEnd()Returns the characters that indicate the end of a comment in the current language context. For languages with line comments, the return value is empty.
commentStart()Returns the characters that indicate the start of a comment in the current language context. For languages with line comments, the return value is the start of a line comment, same as lineCommentStart().
complete()Invokes code completion at the position of the variable.
concat(<String>, ...)

Returns a concatenation of all the strings passed to the function as parameters.

For example, concat(date()," ",user()) returns the current system date and username separated with a space.

dartIterableVariable()Returns the name of a variable that can be iterated.
dartListVariable()Returns a list of elements of an array.
dartSuggestIndexName() Returns a suggested name for an index variable from most commonly used ones: i, j, k, and son on. The names that are not used in the current scope yet are shown first.
dartSuggestVariableName() Returns the suggested name for a variable based on its variable type and initializer expression, according to your code style settings that refer to the variable naming rules.
For example, if it is a variable that holds an element within an iteration, WebStorm makes a guess on the most reasonable name, taking into account the name of the container that is iterated.
date([format])

Returns the current system date.

By default, without a parameter, it returns the date in the current system format. To use a different format, provide a parameter according to the SimpleDateFormat specification. For example, the date("Y-MM-d, E, H:m") returns the date formatted as 2020-02-27, Thu, 16:11.

dbColumns()

Returns a list of columns for a table or a view. The dbColumns() is used in context live templates (for example, ins). You can access context live templates by right-clicking an object and selecting SQL Scripts.

dbObjectName()

Returns a name of a table or a view. The dbObjectName() is used in context live templates (for example, top). You can access context live templates by right-clicking an object and selecting SQL Scripts.

decapitalize(<String>)

Replaces the first letter of a string with the corresponding lowercase letter.

For example, decapitalize("Name") returns name.

defaultReturnValuesReturns the default value if the expression is used in the return statement. Uses the errorVariableName parameter if the expression is of the error type.
enum(<String>, ...)

Returns a list of strings suggested for completion when the template expands.

For example, enum("Foo","Bar","Baz") shows a list from which you can choose one of the specified strings.

escapeString(<String>)

Escapes special characters so that the result can be used in a Java string.

For example, it replaces the tab character with \t, the newline character with \n, escapes the backslash as \\, quotes as \", and so on.

expectedType()Returns the expected type of the expression where the template expands (in the right part of an assignment, after return, as a method parameter, and so on).
fileName()Returns the name of the current file with its extension.
fileNameWithoutExtension()Returns the name of the current file without its extension.
filePath()Returns the absolute path to the current file.
fileRelativePath()Returns the current file path relative to the current project. To check what the relative path is for a given file, right-click it and select Copy Reference, or press Ctrl+Alt+Shift+C.
firstWord(<String>)

Returns the first word of the string passed as the parameter.

For example, firstWord("one two three") returns one.

groovyScript(<String>, [arg, ...])

Executes the Groovy script passed as a string.

The first argument is a string with either the text of the script or the path to the file that contains the script. The function passes other optional arguments to the script as values for _1, _2, _3, ..., _n variables. Also, you can access the current editor from inside the script using the _editor variable.

The following example shows a groovyScript() function that splits the selected text into words and displays them as a numbered list:

groovyScript("def result = ''; _1.split().eachWithIndex { item, index -> result = result + index.next() + '. ' + item + System.lineSeparator() }; return result;", SELECTION);
JsArrayVariable()Returns the name of the current JavaScript array.
jsClassName()Returns the name of the current JavaScript class.
jsComponentTypeOf()Returns the type of the current JavaScript component.
jsDefineParameterBased on the name of the module, returns the parameter from define(["module"], function (<parameter_in_question>>) {}).
jsMethodName()Returns the name of the current JavaScript method.
jsQualifiedClassName()Returns the complete name of the current JavaScript class.
jsSuggestDefaultVariableKind(Boolean)The Boolean parameter determines whether constants are allowed or not in the current context. If no parameter is specified, constants are allowed. When the templates expands, a list is shown with var, let, const options for TypeScript and ES6 and with only one var option for earlier JavaScript versions.
jsSuggestImportedEntityName()Suggests the name for import statements of the type `import * as $ITEM$ from "$MODULE$"` or `import $ITEM$ from "$MODULE$"` based on the filename.
jsSuggestIndexName() Returns a suggested name for an index variable from most commonly used ones: i, j, k, and son on. The names that are not used in the current scope yet are shown first.
jsSuggestVariableName() Returns the suggested name for a variable based on its variable type and initializer expression, according to your code style settings that refer to the variable naming rules.
For example, if it is a variable that holds an element within an iteration, WebStorm makes a guess on the most reasonable name, taking into account the name of the container that is iterated.
lineCommentStart()Returns the characters that indicate the start of a line comment in the current language context.
lineNumber()Returns the current line number.
lowercaseAndDash(<String>)Converts a string into lower case and inserts n-dashes as separators. For example, lowercaseAndDash("MyExampleName") and lowercaseAndDash("my example name") both return my-example-name.
regularExpression(<String>, <Pattern>, <Replacement>)Finds all occurrences of Pattern in a String and replaces them with Replacement. You can specify the pattern as a regular expression to find everything that matches it in the string.
snakeCase(<String>)Converts a string into snake_case. For example, snakeCase("fooBar") and snakeCase("foo bar") both return foo_bar.
spaceSeparated(<String>)Returns the specified string with spaces as separators. For example, spaceSeparated("fooBar") returns foo Bar and spaceSeparated("Foo_BAR") returns Foo BAR.
spacesToUnderscores(<String>)Replaces spaces with underscores in the string passed as the parameter. For example, spacesToUnderscores("foo bar BAZ") returns foo_bar_BAZ.
substringBefore(<String>, <Delimeter>)Returns the substring up to the specified delimiter. This is helpful for removing the extensions in test file names. For example, substringBefore(fileName(),".") returns component-test if used in a file named component-test.js.
time([format])

Returns the current system time.

By default, without a parameter, it returns the time in the current system format. To use a different format, provide a parameter according to the SimpleDateFormat specification. For example, the time("H:m z") returns the time formatted as 13:10 UTC.

underscoresToCamelCase(<String>)Transforms a string with underscores (like snake_case) into camelCase. For example, underscoresToCamelCase(foo_bar_baz) and underscoresToCamelCase(FOO_BaR_baZ) both return fooBarBaz.
underscoresToSpaces(<String>)Transforms underscores in a string to spaces. For example, underscoresToSpaces(foo_bar_baz) returns foo bar baz and underscoresToSpaces(FOO_BaR_baZ) returns FOO BaR baZ.
user()Returns the name of the current user.

Example

Let’s create an ngcomp template for an Angular component, similar to the default a-component. The template will have 3 variables:

  • The first one, $ComponentName$, will become a placeholder for the name of the new component class.

  • The second one, $selector$, will become the name of the component selector.

  • The third one, $END$, indicates where the cursor should be at the end after the template is expanded and the $ComponentName$ and $selector$ placeholders are filled in.

  1. In the editor, select the code you want to use in the template, press Ctrl+Shift+A, and invoke the Save as Live Template… action.

    Select code to save as live template
  2. Enter the abbreviation that you’ll be using to invoke the template, for example, ngcomp, and add a template description, for example, New Angular component.

    Add template abbreviation and description
  3. Add the variables to the template.

    • Replace SearchComponent with $ComponentName$.

    • Add selector: $selector$, inside Component({}).

    • Add $END$ to ngOnInit(){}.

    Add variables
  4. According to the Angular Style Guide, selector names are usually a dashed-case version of the component name, so it would make sense to specify the component name first. However, the selector comes first in the code.

    To solve the problem, click Edit variables and adjust the order of variables using the arrow icons. Now ComponentName comes first and the caret will jump to it first on template expansion.

    Change the order of variables
  5. It would be great if we could specify only the class name and have the selector name filled in automatically through the class name transformation. To do this, click the Expression field next to the selector variable, select the lowercaseAndDash function from the list, and then type ComponentName as its parameter.

    Edit template variables
  6. Optionally:

    You can select Skip if defined next to selector. In that case, after you edit the component name and press Enter, the cursor will go to the $END$ position and not to $selector$.

Let’s see our new template in action:

Expand parameterized template
Last modified: 09 April 2021