Groovy: escape curly braces inside string
I am coding in groovy and am trying to return some javascript. Here is the issue I need to return a string that contains a curly brace and of course groovy reads that as an error. Here is a simple example:
${ i == 0 ? '{' : '}, {' }
I want to return either:开发者_如何学运维
{ or }, { plan and simple.${ i == 0 ? 'should be left brace' : "should be right brace coma left brace" }
Can curly braces be escaped, similar to escaping quotes?
I have tried:${ i == 0 ? '\{' : '\}, \{' }
and
${ i == 0 ? '{{' : '}}, {{' }
Thanks.
I assume that problem occurs in a GSP page. The error you probably get should look similar to this one:
expecting ''', found '\n' @ line 57, column 80.
it) { return i == 0 ? '{' : ' })
One solution is to use the Unicode representation for left and right curly braces:
${ i == 0 ? "\u007B" : "\u007D,\u007B" }
This works for me:
def i = 1
assert "},{" == "${i == 0 ? '{' : '},{'}"
精彩评论