As I slowly crawl in my transition from .net to Java, I find more and more interesting things about the eclipse IDE. I recently stumbled upon its templates and I'm loving it. Which brings me to a question: can I call a template from within a template? Of course it would be merely a copy and paste matter, but I'm wondering if it can be done.
Asked
Active
Viewed 849 times
8
-
1Can you clarify what you are trying to do? Eclipse doesn't have mechanism to expand template inside another template, but you can copy & paste if you need to. – Danail Nachev Jun 14 '11 at 11:30
-
@Pakka, I'm looking at the default "New Java Files" template and it uses four unique sub-templates. It's not really that big a deal. Just make sure that your set of templates forms a directed acyclic graph and you won't have recursive template problems. – Bob Cross Aug 01 '11 at 13:12
1 Answers
5
Yes, actually, you can and there is an example right in the default set.
If you go to your Preferences -> Java -> Code Style -> Code Templates, you can Export All of the provided Java templates. In there you will see the following File template (formatted for readability):
<template
autoinsert="true"
context="filecomment_context"
deleted="false"
description="Comment for created Java files"
enabled="true"
id="org.eclipse.jdt.ui.text.codetemplates.filecomment"
name="filecomment">
/** * */
</template>
and a bit further down, the New Type which makes use of that File template:
<template
autoinsert="true"
context="newtype_context"
deleted="false"
description="Newly created files"
enabled="true"
id="org.eclipse.jdt.ui.text.codetemplates.newtype"
name="newtype">
${filecomment} ${package_declaration} ${typecomment} ${type_declaration}
</template>
So, if you'd like to make a template use another, the basic form is to refer to the id of your sub-template with the dollar sign prefix. For example:
<template
autoinsert="true"
context="BobOuter_context"
deleted="false"
description="Bob example outer template"
enabled="true"
id="bob.example.outertemplate"
name="BobOuter">
BobOuterBegins Insert inner template ${bob.example.innertemplate} BobOuterEnds
</template>
<template
autoinsert="true"
context="BobInner_context"
deleted="false"
description="Bob example inner template"
enabled="true"
id="bob.example.innertemplate"
name="BobInner">
BobInnerBegins Super awesome content goes here BobInnerEnds
</template>

Bob Cross
- 22,116
- 12
- 58
- 95
-
1Is it possible to accomplish this directly in the built-in template editor? – faintsignal Nov 21 '16 at 21:20