Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter into code-template in eclipse-plugin

I want to create a plugin which defines a new code template (like this blog post). How can I pass a parameter into the template? like ${name:param}?

like image 428
IAdapter Avatar asked Oct 16 '09 11:10

IAdapter


2 Answers

There aren't many things that you can pass into a code template. For example ${word_selection} contains the current selection.

But what many people are missing is that you can define your own variables:

private static final ${type} ${name} = new ${type} (${cursor});

Neither ${type} nor ${name} are in the list which you get when you click the "Insert variable..." button. Eclipse notices and allows you to cycle through them with Tab and it will keep the content of these custom "template fields" in sync (so you the part after new gets filled in if you type in the first field).

See this answer for other useful Eclipse templates.

[EDIT] According to the answers in the blog post which you mention, this is only possible at the moment with editor templates, not code templates. I suggest to file a bug against JDT Text to open the API for this.

like image 88
Aaron Digulla Avatar answered Oct 20 '22 11:10

Aaron Digulla


This solution is aimed at Eclipse 4.2 Juno, I have not tested this in any other environment.

All you have to do is pass your parameters, and then you'll have them available.

Say we wanted to create a TemplateVariableResolver that would uppercase the first letter of a passed parameter.

You'll first populate your plugin.xml as follows:

<extension point="org.eclipse.ui.editors.templates">
    <resolver class="org.eclipse.ui.templates.UppercaseResolver"
        contextTypeId="java"
        description="${Uppercase(word[, word...])}  uppercase's the provided words"
        name="Uppercase words" type="Uppercase"/>
</extension>

You'd also create your custom resolver:

public void resolve(TemplateVariable variable, TemplateContext context) {
    if (variable.getVariableType().getParams().size() > 0) {
        StringBuffer result = new StringBuffer();
        for(String value : (List<String>) variable.getVariableType().getParams()) {
            value = value.substring(0,1).toUpperCase() + value.substring(1);
            result.append(value);
        }
        variable.setValue(result.toString());
    }
}

Finally in your code Template:

String name = ${Uppercase(jim,laughlin)};
like image 35
SomeInternetGuy Avatar answered Oct 20 '22 11:10

SomeInternetGuy