7th November 2014

Using PhpStorm's Live Templates for t functions

Chris Hilditch
Developer

At Deeson's PhpStorm is our IDE of choice. Working with PhpStorm's Live Templates can save you some valueable time. In this post I'll show you how to use Live Templates to surround strings in simple t functions in template files.

Live templates

PhpStorm’s Live Templates are chunks of code which can be quickly inserted into a file. Surround Live Templates allow you to select a piece of text and surround it with template.

Drupal's t function

It's Drupal best practice to wrap all strings in a t function - this allow the sting to be translated. In a template file this looks like:

<span><?php print t('This is good Practice'); ?></span>

On most sites there will be hundreds of these strings, so anything that can shave off time will be worthwhile.

Take a look

Here’s an example of Surround Live Templates in action. It’s quick and easy to surround a string with a simple t function.

 

Shortcuts

To show the Surround Live Template list on Macs use Cmd+Alt+J and if you are on a Windows machine use Ctrl+Alt+J.

Setting up Live Templates

To set up a Surround Live Template, go to Preferences > Live Templates and click the plus symbol in the top right of the window.

A Surround Live Template needs to have ‘$SELECTION$’ in it, which is replaced with the selected text. The template also need to be available in the correct contexts.

Here's one I prepared earlier...

PHPStorm templates

 

Have a go

To set up this T string Surround Live Template, the template text needs to be:

<?php print t('$SELECTION$'); ?>

It needs to be applicable in the ‘HTML’ context.

That’s it! You should now be able to use the template. Let us know if you've got any PhpStorm tips too.