antlr / stringtemplate4

StringTemplate 4
http://www.stringtemplate.org
Other
956 stars 231 forks source link

ST throws exception when the template has a scala code that includes string interpolation #277

Closed shivam-880 closed 3 years ago

shivam-880 commented 3 years ago

I have a following piece of template (scala code) that I am trying to use but ST throws exception as mentioned below.

Template 1

rule(query) ::= <<
    val startTimeFilter = s"$EVT_TS > '${startTime.get}'"
    val endTimeFilter = if (endTime.nonEmpty) Some(s"$EVT_TS < '${endTime.get}'") else None

    val q1 = <query>
>>

Exception

resources 2:81: invalid character '''
resources 2:81: invalid character '$'
resources 2:96: invalid character '''
resources 4:38: EOF in string
resources 2:96: ''") else None

    val q1 = <query>' came as a complete surprise to me
Exception in thread "main" java.lang.NullPointerException
    at org.stringtemplate.v4.STGroup.loadTemplateFile(STGroup.java:722)
    at org.stringtemplate.v4.STGroupDir.loadTemplateFile(STGroupDir.java:182)
    at org.stringtemplate.v4.STGroupDir.load(STGroupDir.java:142)
    at org.stringtemplate.v4.STGroup.lookupTemplate(STGroup.java:280)
    at org.stringtemplate.v4.STGroup.getInstanceOf(STGroup.java:215)

What I noticed that the following works just fine:

Template 2

rule(query) ::= <<
    val startTimeFilter = s"$EVT_TS > '${startTime.get}'"

    val q1 = <query>
>>

Code

object Builder extends App {
  val group = new STGroupDir("./builder/src/main/resources")
  val st = group.getInstanceOf("rule")
  val query = """abc"""
  st.add("query", query)
  val result = st.render()
  println(result)
}

Could anyone pls explain this? And how can I fix it?

shivam-880 commented 3 years ago

Figured out! I had to escape the "<" character in the following line like so:

    val endTimeFilter = if (endTime.nonEmpty) Some(s"$EVT_TS \< '${endTime.get}'") else None

Thanks anyway!