Note that there are some explanatory texts on larger screens.

plurals
  1. POTake Mustache Template, pass JSON and Convert to HTML
    primarykey
    data
    text
    <p>I am using this code below to merge JSON data into a template, to get HTML:</p> <p>Template:</p> <pre><code>String schema = "&lt;h1&gt;{{header}}&lt;/h1&gt;" + "{{#bug}}{{/bug}}" + "{{#items}}" + "{{#first}}" + "&lt;li&gt;&lt;strong&gt;{{title}}&lt;/strong&gt; + &lt;/li&gt;" + "{{/first}}" + "{{#link}}" + "&lt;li&gt;&lt;a href=\"{{url}}\"&gt;{{name}} + &lt;/a&gt;&lt;/li&gt;" + "{{/link}}" + "{{/items}}" + "{{#empty}}" + "&lt;p&gt;The list is empty.&lt;/p&gt;" + "{{/empty}}"; </code></pre> <p>JSON object:</p> <pre><code>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&lt;String,String&gt; ctx = new HashMap&lt;String,String&gt;(); 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. } </code></pre> <p>I pass a map of data to get Mustache to work. The method looks like this:</p> <pre><code>public static Map&lt;String, Object&gt; toMap(JSONObject object) throws JSONException { Map&lt;String, Object&gt; map = new HashMap(); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); map.put(key, fromJson(object.get(key))); } return map; } </code></pre> <p>I am following a <a href="http://mustache.github.com/mustache.5.html" rel="nofollow">Mustache Guide</a> to get the Mustache autoformation. But I don't know how to get the result I am expecting. The output should be as follows: </p> <pre><code>&lt;h1&gt;Colors&lt;/h1&gt; &lt;li&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#Green"&gt;green&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#Blue"&gt;blue&lt;/a&gt;&lt;/li&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload