Groovy web console

subscribe to the feed Subscribe
to this
site
Simple Template processor (via #groovywebconsole)
tweet this snippet Tweet
this
script

Simple Template processor

Published 10 months ago by Luis G. Epifanio with tags Simple Template processor
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.util.regex.Matcher



String processMarkupIn(String demo, Map keysInCode){
  String result = demo 
  def tagregex = /\{\%(.+?)\}/

  Matcher matcher = ( demo =~ tagregex )

  Set<String> keys = []
  if( matcher.getCount() > 0 ){
    keys = (0..(matcher.getCount()-1)).collect{
      return matcher[it][1]
    }
  }

  if(! keysInCode.keySet().containsAll(keys)){
    throw new IllegalArgumentException("something is missing " + keys.findAll{ !keysInCode.keySet().contains(it) } )
  }else{

  for(String key : keys){
    String what = "{%$key}"
    String withString = keysInCode[key]
    result = result.replace(what, withString)
  }
  
}

return result

}

Map customKeys = [
  'TAGA' : '<div>',
  'TAGC' : '</div>'
]

String justAString = "Esta es una key que tiene {%TAGA} Mercado Pago {%TAGC} y por ac?mas texto"
println processMarkupIn(justAString, customKeys)