【问题标题】:Take Mustache Template, pass JSON and Convert to HTML获取 Mustache 模板,传递 JSON 并转换为 HTML
【发布时间】:2013-03-10 17:14:01
【问题描述】:

我正在使用以下代码将 JSON 数据合并到模板中,以获取 HTML:

模板:

String schema = "<h1>{{header}}</h1>"
    + "{{#bug}}{{/bug}}"
    + "{{#items}}"
    + "{{#first}}"
    + "<li><strong>{{title}}</strong>
    + </li>"
    + "{{/first}}"
    + "{{#link}}"
    + "<li><a href=\"{{url}}\">{{name}}
    + </a></li>"
    + "{{/link}}"
    + "{{/items}}"
    + "{{#empty}}"
    + "<p>The list is empty.</p>"
    + "{{/empty}}";

JSON 对象:

try {
    String template = "{\"header\": \"Colors\", "
        + "\"items\": [ "
        + "{\"name\": \"red\", \"first\": true, \"url\": \"#Red\"}, "
        + "{\"name\": \"green\", \"link\": true, \"url\": \"#Green\"}, "
        + "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"}"
        + " ], \"empty\": false }";

    JSONObject jsonWithArrayInIt = new JSONObject(template); 
    JSONArray items = jsonWithArrayInIt.getJSONArray("items"); 

    Map<String,String> ctx = new HashMap<String,String>();
    ctx.put("foo.bar", "baz");
    Mustache.compiler().standardsMode(true).compile("{{foo.bar}}").execute(ctx);

    System.out.println("itemised: " + items.toString());
} catch(JSONException je) {
    //Error while creating JSON.
}

我传递了一张数据图来让 Mustache 工作。该方法如下所示:

public static Map<String, Object> toMap(JSONObject object)
        throws JSONException {
    Map<String, Object> map = new HashMap();
    Iterator keys = object.keys();

    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)));
    }

    return map;
}

我正在关注 Mustache Guide 以获取 Mustache 自动化。但我不知道如何得到我期望的结果。输出应该如下:

<h1>Colors</h1>
<li><strong></strong></li>
<li><a href="#Green">green</a></li>
<li><a href="#Blue">blue</a></li>

【问题讨论】:

    标签: java html json mustache


    【解决方案1】:

    我认为您需要稍微重新考虑您的 Mustache 模板。 jMustache 库(我假设您正在使用)似乎总是将 {{# 实体视为列表并迭代其内容,而不管传入的数据类型如何。

    这样的事情应该可以工作:

    <h1>{{header}}</h1>
    {{#items}}
    <li>
        {{#url}}<a href="{{.}}">{{/url}}
        {{^url}}<strong>{{/url}}
            {{caption}}
        {{#url}}</a>{{/url}}
        {{^url}}</strong>{{/url}}
    </li>
    {{/items}}
    {{^items}}
        <p>The list is empty.</p>
    {{/items}}
    

    仅当提供“链接”值时才会生成 HMTL 锚点,从而避免 jMustache if 条件问题。所以 JSON 模型看起来像这样:

    {
    "header": "Colors",
    "items": [
            {"caption": "title"},
            {"caption": "red", "url": "#Red"},
            {"caption": "green", "url": "#Green"},
            {"caption": "blue", "url": "#Blue"}
        ]
    }
    

    最后,您需要将 JSON 转换为 jMustache 可以理解的内容。在我使用过的任何库中,我从未见过或听说过“HTTPFunctions”类,但我过去曾使用 Gson 做过一些类似的映射。请注意,这是一个非常简单的实现,您可能需要对其进行扩展以满足您的需求:

    private Map<String, Object> getModelFromJson(JSONObject json) throws JSONException {
        Map<String,Object> out = new HashMap<String,Object>();
    
        Iterator it = json.keys();
        while (it.hasNext()) {
            String key = (String)it.next();
    
            if (json.get(key) instanceof JSONArray) {
    
                // Copy an array
                JSONArray arrayIn = json.getJSONArray(key);
                List<Object> arrayOut = new ArrayList<Object>();
                for (int i = 0; i < arrayIn.length(); i++) {
                    JSONObject item = (JSONObject)arrayIn.get(i);
                    Map<String, Object> items = getModelFromJson(item);
                    arrayOut.add(items);
                }
                out.put(key, arrayOut);
            }
            else {
    
                // Copy a primitive string
                out.put(key, json.getString(key));
            }
        }
    
        return out;
    }
    

    这个基本的 JUnit 测试演示了理论:http://www.pasteshare.co.uk/p/841/

    【讨论】:

      【解决方案2】:

      随便用

      Map<String, Object> s =  HTTPFunctions.toMap(new JSONObject(template));
      

      【讨论】:

      • 谢谢 :) 但现在如何将其转换为 html 格式模板?
      • 虽然代码很受欢迎,但它应该始终有一个附带的解释。这不必很长,但在意料之中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      相关资源
      最近更新 更多