简体   繁体   中英

How can I render all the values of each jsonObject in a jsonArray with Pebble templetes engine and Java with vertx library?

This is my template:

 <tbody id="byCountry"> {% for dataFilm in film %} <tr> <td>{{Date}}</td> <td>{{Title}}</td> <td>{{MainActor}}</td> </tr> {% endfor %} </tbody>
But, should I define "dataFilm" in somewhere? This is my Java code with vertx:

 summary.onComplete(jsonObjectAsyncResult -> { if (jsonObjectAsyncResult.succeeded()) { JsonArray summaryArray = jsonObjectAsyncResult.result().getJsonArray("Films"); JsonObject filmInfo = new JsonObject(); for( int i = 0; i<summaryArray.size(); i++){ filmInfo.put("summaryArray",summaryArray).put("Date", summaryArray.getJsonObject(i).getString("Date")).put("Title", summaryArray.getJsonObject(i).getString("Title")).put("MainActor", summaryArray.getJsonObject(i).("MainActor")); engine.render(filmInfo, "webroot/templates/films.peb", res ->{ if (res.succeeded()) { routingContext.response().end(res.result()); } else { routingContext.fail(res.cause()); } });

The problem here is when I've tried to render, only rendered the first film or the last film because I have to end the response with the engine.render... Any idea that how I should to do it?

I don't know pebble templates, but seems you messed up your processing logic, try something like this

if (jsonObjectAsyncResult.succeeded()) {
        JsonArray summaryArray = jsonObjectAsyncResult.result().getJsonArray("Films");
        List<Map<String, Object>> list = new ArrayList<>();
        for(int i=0; i<summaryArray.size(); i++) {
             list.add(summaryArray.getJsonObject(i).getMap());
        }
        Map<String, Object> templateVars = new HashMap<>();
        templateVars.put("films", list);

        engine.render(templateVars, "webroot/templates/countries.peb", res ->{
                if (res.succeeded()) {
                        routingContext.response().setStatusCode(200).end(res.result());
                } else {
                        routingContext.fail(res.cause());
                }
        });
}

and template code:

 <tbody id="byCountry">
 {% for dataFilm in films %}
     <tr>
        <td>{{dataFilm.Date}}</td>
        <td>{{dataFilm.Title}}</td>
        <td>{{dataFilm.MainActor}}</td>                    
    </tr>
{% endfor %}
</tbody>```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM