Twig遍历对象内数组无输出且无报错,求正确实现方案
Twig遍历products数组生成结构化数据问题解决
原始数据结构
用户提供的包含产品数组的对象:
{ "products": [ { "title": "product", "ID": "1", "price": "€ 85,00 ", "discount": "€ 59,50 ", "discountperc": "30 %", "stars": "2", "prodnew" : "", "images": "http://127.0.0.1/image.png" }, { "title": "product", "ID": "2", "price": "€ 180,00 ", "discount": "", "discountperc": "", "stars": "", "prodnew" : "", "images": "http://127.0.0.1/image.png" } ] }
用户的错误尝试
用户使用以下Twig代码遍历数组,但无任何输出:
{% for item in dummy.products %} {{item.title}} { "@type": "Product", "name": "{{item.title}}", "price": "item.price", "image": "item.images" }, {% endfor %}
解决步骤
1. 先验证变量有效性
首先确认dummy对象以及dummy.products是否正确传入模板,这是无输出的常见原因。添加调试代码:
{# 检查变量是否存在且有数据 #} {% if dummy is defined and dummy.products is defined %} 产品总数:{{ dummy.products|length }} {% else %} 变量dummy或products未定义 {% endif %}
2. 修正变量输出与JSON格式
原代码存在两个核心问题:
- 未用Twig语法输出
price和image变量,直接写了字符串"item.price" - 生成的JSON会有末尾多余逗号,导致格式非法
正确实现代码:
{% if dummy is defined and dummy.products is iterable %} [ {% for item in dummy.products %} { "@type": "Product", "name": "{{ item.title|escape('json') }}", "price": "{{ item.price|trim|escape('json') }}", "image": "{{ item.images|escape('json') }}" {% if item.discount %} , "discountPrice": "{{ item.discount|trim|escape('json') }}" {% endif %} {% if item.discountperc %} , "discountPercentage": "{{ item.discountperc|trim|escape('json') }}" {% endif %} }{% if not loop.last %},{% endif %} {% endfor %} ] {% endif %}
关键说明
- 用
{{ 变量 }}语法输出动态值,替代硬编码字符串 |escape('json')确保变量中的特殊字符(如引号)不会破坏JSON结构|trim清理价格等字段的前后空格loop.last控制逗号,避免最后一个产品后出现多余逗号- 增加变量检查,防止因变量未定义导致的静默错误
内容的提问来源于stack exchange,提问作者Vincenzo
相关产品推荐
相关产品推荐

