如何用Mustache模板渲染API返回的键值对生成Materialize卡片
First off, let's get your JSON into valid shape (unquoted keys aren't allowed in standard JSON) and then walk through how to use Mustache to render those Materialize cards exactly as you want.
Step 1: Fix Your JSON Data
Your original JSON has unquoted keys and a minor typo ("teusday" → "tuesday" — feel free to revert if that's intentional). Here's the valid version:
{ "dailytask": [ { "title": "Chores", "body": "Wash the plates and vacuum the living room" } ], "monday": [ { "title": "madrid", "body": "Wash the roof and sweep the bed" }, { "title": "opopo", "body": "Wash the roof and sweep the bed" } ], "tuesday": [ { "title": "exercises", "body": "jog 5k, lift and cardio" }, { "title": "read", "body": "read up on kubernetes and Docker" } ], "wednesday": [ { "title": "read", "body": "continue learning VUE.js" }, { "title": "shop", "body": "buy some clothes and a new mouse" } ] }
Step 2: Transform Data for Mustache
Mustache is logic-less, so it doesn't natively loop through object keys. We'll convert your object into an array of groups (each with a name and list of tasks) to make iteration straightforward:
// Your valid JSON data const taskData = { /* paste the valid JSON here */ }; // Transform into an array of groups with capitalized names for better display const formattedData = Object.entries(taskData).map(([groupName, tasks]) => ({ groupName: groupName.charAt(0).toUpperCase() + groupName.slice(1), tasks: tasks }));
This gives us an array where each entry looks like:
{ "groupName": "Monday", "tasks": [ /* array of task objects */ ] }
Step 3: Create the Mustache Template
We'll write a template that loops through each group, then each task in the group to generate your Materialize cards. Use ../groupName to access the parent group name inside the tasks loop:
<!-- Save this in a script tag with id="taskCardTemplate" --> <script type="text/template" id="taskCardTemplate"> {{#formattedData}} {{#tasks}} <div class="col s12 m6"> <div class="card blue-grey darken-1"> <div class="card-content white-text"> <span class="card-title">{{title}}</span> <p>{{body}}</p> </div> <div class="card-action"> <span>{{../groupName}}</span> </div> </div> </div> {{/tasks}} {{/formattedData}} </script>
Step 4: Render the Template
Load the Mustache library (via CDN or local file), then render and insert the HTML into your page:
// Get the template and render it with our formatted data const template = document.getElementById('taskCardTemplate').innerHTML; const renderedCards = Mustache.render(template, { formattedData }); // Insert into your container element (e.g., a div with id="taskContainer") document.getElementById('taskContainer').innerHTML = renderedCards;
That's it! This will generate a Materialize card for every task, with the group name (like Monday, Dailytask) displayed in the card's action section.
内容的提问来源于stack exchange,提问作者Nathaniel Babalola

