使用Mustache+Pattern Lab时模板片段无法遍历传入数据求助
Let's break down why your template isn't working and fix it step by step:
1. Map Your Data Hierarchy First
First, let's recap your data structure to make sure we're traversing it correctly:
{ "states": { "dropdown": { "items": [ /* array of state objects */ ] } }, "roles": { "dropdown": { "items": [ /* array of role objects */ ] } } }
Your states is an object (not an array), containing a dropdown object, which in turn holds the items array you want to loop through. Mustache requires you to traverse each level explicitly—you can't skip levels with dot notation inside a section opening.
2. Correct the Template Section Nesting
Your current template starts with {{#states}} {{#dropdown.items}} which won't work because of the invalid section syntax. Here's the fixed version for the states dropdown:
{{#states}} {{#dropdown}} {{#items}} {{title}} <!-- This will output CA, OR, TX --> {{/items}} {{/dropdown}} {{/states}}
{{#states}}enters the context of thestatesobject{{#dropdown}}then moves into thedropdownsub-object{{#items}}finally loops through the array of state items
3. Add Proper Closing Sections
Your original code cuts off with {{...—don't forget Mustache requires every opening {{#section}} to have a matching {{/section}} tag. Missing closures will break template rendering entirely.
4. Bonus: Render Both Dropdowns (and Keep Code DRY)
If you want to render both states and roles, you can reuse the same pattern, or even create a Pattern Lab partial for dropdowns to avoid repetition:
<!-- States Dropdown --> <h3>Select a State</h3> <select> {{#states.dropdown.items}} <option>{{title}}</option> {{/states.dropdown.items}} </select> <!-- Roles Dropdown --> <h3>Select a Role</h3> <select> {{#roles.dropdown.items}} <option>{{title}}</option> {{/roles.dropdown.items}} </select>
(Note: This alternative uses full dot notation directly on the array section, which works if you don't need to access other properties in the states or dropdown objects.)
5. Quick Checks for Pattern Lab
- Verify your data file is placed in the correct
_datadirectory - If using template variants, ensure the data context is properly linked to your snippet
- Clear Pattern Lab's cache if you're still seeing old results
内容的提问来源于stack exchange,提问作者mheavers

