Paul Robertson's words, punctuated

Thoughts on development, user-centered design, code, etc. by Paul Robertson

Flash Builder 4.5 Tip: Customize templates and create your own

I’ve written about using templates in Flash Builder 4.5. However, chances are you’re going to want to edit some of the templates that come with Flash Builder 4.5, and create your own. Admittedly I’ve become a bit addicted to templates, so I have a rule for myself that once I need a particular block of code more than a couple of times, I stop and turn it into a template.

Here’s an example of editing one of the pre-installed code templates. This is one of the first changes I made, editing the “fori” template (which creates a for loop) to use a variable for the array’s length instead of referencing the Array.length property:

  1. open Flash Builder preferences
  2. expand the Flash Builder > Editors > Code Templates section
  3. choose the category for the template you want to edit (“ActionScript” in this case)

  4. Scroll the list and select the “fori” template. Click the “Edit” button.
  5. Replace the code block with the following code:

    for (var ${index}:int = 0, len:int = ${array}.length; ${index} < len; ${index}++)
  6. Choose “OK” and the template is updated.

Adding a template variable

In this case the code in the for loop just declares a variable named len that stores the array’s length value. If you want to customize the name of the variable that stores the length property, you can use a template variable in place of the hardcoded len.

Template variables are specified using the following syntax:


In this example, if you use the same variable name in both places where len appears in the template then when you’re using the template you will only have to change it once to have it change everywhere in the template. For example, to make the len variable a template variable, use this code:

for (var ${index}:int = 0, ${len}:int = ${array}.length; ${index} < ${len}; ${index}++)

The name you give to the variable (the text between the curly braces) is the default text that’s inserted into the template.

Special template variables

In addition to your own custom template variables, there are also several built-in template variables that have special values. Some of these are “constant” values for a given file–for example, the ${enclosing_type} variable inserts the name of the current class. Others use the code model to populate a list of choices. For instance, the ${field} variable gives you a list of all the class-level variables and the ${local_var} variable gives you a list of all the variables that are in-scope in the current method.

To see the list of built-in template variables, click the “Insert Variable…” button or just type “$” and a code-hint menu will appear.

Once you’ve created your own templates, make sure to share your templates with others so we can steal benefit from your ideas.