如何在java中获取胡子html

时间:2015-06-02 17:56:40

标签: java mustache

我尝试使用小胡子为我填写html,然后我想获取该html并将其用作String。

像这样的模板 - >的template.xhtml

<table style="width:10%" align="center">
    <tr>
        <th>Old</th>
        <th>New</th>
    </tr>
    <tr>
        <td>{{old}}</td>
        <td>{{new}}</td>                                
    </tr>
</table>

使用这样的哈希:

HashMap<String, String> scopes = new HashMap<String, String>();
    scopes.put("old", "Testing");
    scopes.put("new", "Mustache");

现在我该如何判断,Mustache使用template.xhtml并填充范围,然后将html返回给我?

4 个答案:

答案 0 :(得分:1)

查看Mustache项目的自述文件(https://github.com/spullara/mustache.java#readme)的最底部。那里有一个示例main方法几乎完全符合您的需要。只需使用StringWriter代替OutputStreamWriter,这样您就可以将生成的HTML视为String

答案 1 :(得分:0)

String aux = "";    
MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile("path/to/file.html");
    StringWriter stringWriter = new StringWriter();
    mustache.execute(stringWriter, wrapper);
    aux = stringWriter.toString();
    System.out.println(aux);

答案 2 :(得分:0)

我在Android中遇到同样的问题,我将html解析为String:

 public static String readInputStreamAsString(InputStream in)
        throws IOException {

    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
        byte b = (byte)result;
        buf.write(b);
        result = bis.read();
        buf.flush();
    }
    return buf.toString();
}

在数据中填写模板:

  Map<String, String> data = new HashMap<>();
  data.put("data", "123");
  data.put("read_mode","day");
  data.put("font_size","small");
  Template tmpl = Mustache.compiler().compile(readInputStreamAsString(***InputStream)));
  String html = tmpl.execute(data);

它运作正常。

答案 3 :(得分:0)

我正在使用弹簧起动器胡子。

string urlScheme = @"jar:file://";
string apkPath = Application.dataPath;
string separator = @"!/";
string entry = @"classes.dex";
string url = urlScheme + apkPath + separator + entry;

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>

我希望这会有所帮助。