What is an Eclipse template and how do I use it?
Author: Deron Eriksson
Description: This tutorial shows how to use a template in Eclipse
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page:    1 2 >

If you find yourself performing a certain task in your editor window in EclipseSW over and over, this task may be a great candidate for an Eclipse template. What is a template? A template is a chunk of text or code that you can automatically insert into the file that you are working on in your editor using Eclipse's 'control-space' auto-completion feature. It is a fantastic time-saver.

In this tutorial, let's automate the process of creating a jspW header that inserts the page 'contentType' directive and the core, fmt, sqlW, and xmlW JSTLSW taglib directives. So, we are going to create an Eclipse JSP template that inserts the following header into a jsp using auto-complete:

<%@ page contentType="text/html; charset=ISO-8859-1" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

We can get to the Eclipse Templates by going to Window → Preferences. I typed 'Templates' into the filter in the upper left-hand corner to help me find the various templates.

Eclipse Templates

I wanted to create a JSP template, so I clicked on 'JSP Templates' on the left menu and then I clicked the New button.

Eclipse JSP Templates

In the 'New Template' window, I gave my new template the name 'jstl header', set the context to 'New JSP', gave the description 'inserts a header for standard jstlSW taglibs, and then put in the template code into the Pattern section. The Context is set to 'New JSP' so that I can insert the template into the very beginning of the document. Normally, for most templates you can use the Context 'All JSP' so that you can insert it anywhere in the document.

Notice that the first line contains the ${encoding} variable. This automatically substitutes the correct character set into the position of the variable when the template is called on a JSP. Other useful variables let you do things like insert selected text into template and set the position of the Editor cursor after the insertion of the template is completed. The variable choices can be seen by clicking on the Insert Variable button.

Since we are done creating the new 'jstl header' template, we can click OK.

New Template window

(Continued on page 2)

Page:    1 2 >