java - 使用 Mustache 模板,传递 JSON 并转换为 HTML

标签 java html json mustache

我正在使用下面的代码将 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>

最佳答案

我认为您需要稍微重新考虑您的 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}}

仅当提供“链接”值时才会生成 HTML anchor ,从而避免 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/

关于java - 使用 Mustache 模板,传递 JSON 并转换为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15543379/

相关文章:

java - 使用 Java 的 Scanner 类确定文件结尾

java - 使用 spring MultipartFile 和 google app engine 上传文件

Java - 循环遍历 JSONArray

java - 如何找到 HttpURLConnection 尝试将我重定向到的位置?

java - 更改内部类对象的外部类引用

html - 在旧版浏览器上在线测试本地主机网站兼容性

HTML:添加到自动高度以补偿页脚

Javascript FadeIn 无法正常工作

facebook - 使用 Graph API 访问评论的所有回复

json数据的Javascript数据结构