使用速度模板和 JSON 生成 HTML?

Using velocity template and JSON to generate HTML?

我需要一种直接的方法来使用速度模板和 JSON 字符串数据来生成 HTML 数据。 例如:

String mergedHtml = Velocity.someMethodToParseTemplate("VelocityTemplate.vm" ,String JsonString");

怎么办?请建议 "someMethodToParseTemplate"?

的代码

您只需要解析 JSON 字符串(例如使用 org.json library),然后根据解析结果构建 VelocityContext。

假设您有以下模板:

<html>
  <body>
    $name is $age years old and lives $address.streetAddress, ${address.city}.
    <br/>
    $name's friends:
    <ul>
    #foreach($friend in $friends)
      <li>$friend.name, who is $friend.age years old</li>
    #end
    </ul>
  </body>
</html>

您可以像这样将它与 JSON 字符串合并:

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.json.JSONObject;

public class JsonPublisher
{
  protected VelocityEngine velocity;

  public JsonPublisher()
  {
    // init velocity                                                                                                                                                                                            
    // default resource loader is a file loader on the current directory                                                                                                                                        
    velocity = new VelocityEngine();
    velocity.init();
  }

  public String publish(String templatePath, String jsonString) throws IOException
  {
    // translate json string to velocity context                                                                                                                                                                
    // (we only need to convey the properties of the root object)                                                                                                                                               
    JSONObject jsonObj = new JSONObject(jsonString);
    VelocityContext context = new VelocityContext();
    for(String key : jsonObj.keySet())
    {
      context.put(key, jsonObj.get(key));
    }

    Writer writer = new StringWriter();
    velocity.mergeTemplate(templatePath, "UTF-8", context, writer);
    writer.flush();

    return writer.toString();
  }

  public static void main(String args[])
  {
    try
    {
      String str = "{ \"name\": \"Alice\", \"age\": 20, \"friends\": "+
        "[ { \"name\":\"Bob\", \"age\":21 }, { \"name\":\"Carol\", \"age\":19 } ], " +
        "\"address\": { \"streetAddress\": \"100 Wall Street\", \"city\": \"New York\" } }";
      String result = new JsonPublisher().publish("template.vm", str);
      System.out.println(result);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

如果您想将 JSON 对象包装在上下文的某个根 属性 下,比如说 $json,那么它就更简单了:

....
JSONObject jsonObj = new JSONObject(jsonString);
VelocityContext context = new VelocityContext();
context.put("json", jsonObj);        
....

如果要在浏览器中显示 Html 的主要 objective 那么最好分别使用客户端速度渲染引擎和 json + 模板来客户。

如果您的客户端是浏览器,您可以在浏览器上使用velocityjs。 本质上它可以归结为 var renderedHtml = velocityjs.render(htmlTemplate,jsonData) 之类的东西。然后你可以将 renderedHtml 设置为某些 dom 元素的 innerHtml

查看我的