Create a Live Template in PhpStorm
Learn how to create reusable code shortcuts with live templates in PhpStorm.
Lesson Content
One of my favorite PhpStorm features is a Live Template. A Live Template turns a block of code into a repeatable shortcut, so you don’t have to type the same code over and over again.
Open PhpStorm -> Preferences, select Editor, and then choose Live Templates. PhpStorm organizes templates into groups. For example, the Angular group contains templates related to Angular.
Create a group for your own templates by selecting the plus sign and choosing Template Group. Name the group My Live Templates.
Select the plus sign again, but this time choose Live Template. The new template needs an abbreviation, which acts as the keyword that triggers it. We’ll create a simple version of Laravel’s dd() helper, so set the abbreviation to mydd.
The Template text field contains the code that PhpStorm inserts. Add a var_dump() call followed by die():
var_dump($var$);
die();The $var$ portion is a custom template variable. When PhpStorm expands the template, the cursor stops at this variable and lets you enter a value.
PhpStorm also provides special variables. $END$ tells PhpStorm where to place the cursor after it finishes moving through the custom variables. Add it directly after die();, on the same line:
var_dump($var$);
die();$END$When you need a literal dollar sign in a template, use two dollar signs. For example, $$ inserts a single dollar sign instead of being interpreted as a template variable.
Before saving the template, define the context in which it is available. Select Define and enable the PHP context. Without a context, PhpStorm doesn’t know when it should offer the template.
Click OK to save the template. Open a PHP file and type mydd, then press Enter. PhpStorm expands the template and places the cursor at $var$.
Type 'hi!' and press Tab. The cursor moves to $END$, where you can continue writing code. If the template contains multiple custom variables, PhpStorm moves through each one in order until it reaches $END$.
You can create as many template groups and templates as you need, and assign them to different contexts. Live Templates are especially useful for code that you find yourself typing repeatedly.
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.