Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable to groovy code in Intellij IDEA live templates groovy script?

I have a groovyScript in my Intellij IDEA live template, like this :

groovyScript("D:/test.groovy","", v1)

on my D:/test.groovy i have a code like this:

if ( v1 == 'abc') {
    'abc'
}

Now I want to pass v1 variable into test.groovy ,can any one help me how can I do this?

like image 859
Shaiful Avatar asked Feb 15 '16 09:02

Shaiful


People also ask

How do I create a live template in IntelliJ?

Press Ctrl+Alt+S to open the IDE settings and select Editor | Live Templates. Select the template group where you want to create a new live template (for example, other). If you do not select a template group, the live template will be added to the user group. and select Live Template.

Does IntelliJ support Groovy?

The Groovy plugin is bundled with IntelliJ IDEA and enabled by default. IntelliJ IDEA supports the latest stable version of Groovy and Groovy 4 syntax.

What is live template in Android Studio?

Android Studio (and in consequence, IntelliJ) comes with a feature called Live Templates which allow developers to customize shortcuts or abbreviation that translates to written code. Following the previous example, we have a default shortcut for that, in Java and in Kotlin.


3 Answers

For exemplification purposes I made a live template which is printing a comment with the current class and current method.

This is how my live template is defined:

enter image description here

And here is how I edited the variableResolvedWithGroovyScript variable:

enter image description here

The Expression for the given variable has the follwing value:

groovyScript("return \"// Current Class:\" + _1 + \". Current Method:\"+ _2 ", className(),methodName())

As you can see, in this case the _1(which acts like a variable in the groovy script) takes the value of the first parameter which is the class name, and the _2 takes the value of the second parameter which is the method name. If another parameter is needed the _3 will be used in the groovy script to reference the given parameter.

like image 185
dj_frunza Avatar answered Sep 29 '22 06:09

dj_frunza


The arguments to groovyScript macro are bound to script variables named _1, _2 etc. This is also described at groovyScript help at Edit Template Variables Dialog / Live Template Variables.

like image 30
Peter Gromov Avatar answered Sep 29 '22 06:09

Peter Gromov


I found a solution.

I was needing to calculate a CRC32 of the qualified class name using live models

I used it like this:

groovyScript("   
def crc = new java.util.zip.CRC32().with { update _1.bytes; value }; 
return Long.toHexString(crc);  
", qualifiedClassName())

enter image description here

then the result is

enter image description here

like image 25
Arthur Melo Avatar answered Sep 29 '22 06:09

Arthur Melo