3

Python supports the following operation:

>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

(Example taken from Python's official documentation)

Is there an equivalent way in Java for performing the exact task?

Thanks

Omer Dagan
  • 14,868
  • 16
  • 44
  • 60

6 Answers6

4

Take a look at http://www.stringtemplate.org/. Here is an example:

ST hello = new ST("Hello, <name>");
hello.add("name", "World");
System.out.println(hello.render());

prints out:

"Hello World"
Ben Green
  • 3,953
  • 3
  • 29
  • 49
  • does it allow condition based templating? – Gaurav Jan 31 '19 at 10:45
  • 1
    @gaurav Do you mean like this: https://theantlrguy.atlassian.net/wiki/spaces/ST/pages/1409039/Conditionally+included+subtemplates – Ben Green Jan 31 '19 at 14:56
  • Can't access that link but got it working using the official documentation at https://github.com/antlr/stringtemplate4/blob/master/doc/templates.md#conditionals – Gaurav Jan 31 '19 at 15:57
2

Chunk templates (http://www.x5dev.com/chunk) make this kind of thing pretty easy:

Chunk c = new Chunk();
c.append("{$who} likes {$what}");
c.set("who", "tim");
c.set("what", "kung pao");
String output = c.toString();

Or if you have a Map<String,String> already:

Chunk c = new Chunk();
c.append("{$who} likes {$what}");
Map<String,String> tagValues = getTagValues();
c.setMultiple(tagValues);
c.render(System.out);

Chunk also makes it easy to load templates from a file or a group of files, and supports looping, branching, and presentation filters.

Tom McClure
  • 6,699
  • 1
  • 21
  • 21
1

I don't know if there is anything equal, but you can do:

String s = "$who likes $what";
s.replace("$who", "tim").replace("$what", "kung pao");

And you will get the same result.

luanjot
  • 1,176
  • 1
  • 7
  • 21
1

There's another option answered here. Will repeat it for convenience.

There's a library org.apache.commons:commons-text:1.9 with class StringSubstitutor. That's how it works:

 // Build map
 Map<String, String> valuesMap = new HashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";

 // Build StringSubstitutor
 StringSubstitutor sub = new StringSubstitutor(valuesMap);

 // Replace
 String resolvedString = sub.replace(templateString);

Still there's a remark. StringSubstitutor instance is created with a substitution map and then parses template strings with its replace method. That means it cannot pre-parse the template string, so processing the same template with different substitution maps may be less efficient.

The Python's string.Template works the opposite way. It's created with the template string and then processes substitution maps with its substitute or safe_substitute methods. So theoretically it can pre-parse the template string that may give some performance gain.

Also the Python's string.Template will process ether $variable or ${variable} by default. Couldn't find so far how to adjust the StringSubstitutor to do this way.

By default StringSubstitutor parses placeholders in the values that may cause infinite loops. stringSubstitutor.setDisableSubstitutionInValues(true) will disable this behavior.

Nick Legend
  • 789
  • 1
  • 7
  • 21
0

String s = String.format("%s likes %s", "tim", "kung pao");

or

System.out.printf("%s likes %s", "tim", "kung pao");

you can easily do the templating with this too.

String s = "%s likes %s";
String.format(s, "tim", "kung pao");
Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • 2
    This is not helpful for me since I want to initiate the template in one part of the code and make the substitution somewhere else. – Omer Dagan Aug 23 '14 at 10:13
  • 1
    `String.format` is more an equivalent of Python's own string formatting (with `%` or similar `"string".format()`). The fundamental of `Template` is being able to replace custom named regions. – Cwt May 18 '15 at 17:27
0

I think you can use String.format to achieve this.

http://javarevisited.blogspot.sk/2012/08/how-to-format-string-in-java-printf.html

petomalina
  • 2,020
  • 2
  • 19
  • 25