简体   繁体   English

Python中的Python字符串'Template'等效

[英]Python string 'Template' equivalent in java

Python supports the following operation: Python支持以下操作:

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

(Example taken from Python's official documentation ) (来自Python官方文档的示例)

Is there an equivalent way in Java for performing the exact task? 在Java中是否有相同的方法来执行确切的任务?

Thanks 谢谢

Take a look at http://www.stringtemplate.org/ . 看看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"

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. 你会得到相同的结果。

Chunk templates ( http://www.x5dev.com/chunk ) make this kind of thing pretty easy: 块模板( http://www.x5dev.com/chunk )使这种事情变得非常简单:

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: 或者,如果您已经有Map<String,String>

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. Chunk还可以轻松地从文件或一组文件加载模板,并支持循环,分支和表示过滤器。

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");

I think you can use String.format to achieve this. 我认为你可以使用String.format来实现这一目标。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM