Shopify Liquid条件迭代问题:多教师标题拼接错误求助
Fix for Duplicate Course Title in Shopify Liquid Template
Hey there! I see exactly what's going wrong here. Your current code prints the full course title + "with" phrase inside the for loop, so every teacher entry repeats the entire title segment. Let's rewrite this to only show the course title once, then properly format the teacher names.
Solution Code
First, we'll separate capturing the formatted teacher names from the final title string:
{% capture teacher_names %} {% for teacher in course.teachers %} {% if forloop.last and course.teachers.size > 1 %} and {{ teacher.name | escape }} {% elsif forloop.first %} {{ teacher.name | escape }} {% else %} , {{ teacher.name | escape }} {% endif %} {% endfor %} {% endcapture %} {% capture title_tag %} {{ course.title }} with {{ teacher_names | strip }} {% endcapture %}
How This Works
- Capture Teacher Names Separately: We loop through teachers and build a string of names with proper formatting:
- For the first teacher: just output their escaped name
- For middle teachers: add a comma + space before the name (Oxford comma style)
- For the last teacher (when there's more than one): add "and " before their name
- Build the Final Title: Now we only print the course title once, followed by "with" and our pre-formatted teacher names string.
Example Outputs
- Single teacher:
Intro to Maths with Isaac Newton(matches your expected result) - Two teachers:
Intro to Maths with Isaac Newton and Elon Musk - Three teachers:
Intro to Maths with Isaac Newton, Marie Curie, and Elon Musk
Optional: No Oxford Comma
If you prefer to skip the Oxford comma for multiple teachers, adjust the teacher_names capture block like this:
{% capture teacher_names %} {% for teacher in course.teachers %} {% if course.teachers.size == 1 %} {{ teacher.name | escape }} {% elsif forloop.last %} and {{ teacher.name | escape }} {% else %} {{ teacher.name | escape }}, {% endif %} {% endfor %} {% endcapture %}
This will output three teachers as: Intro to Maths with Isaac Newton, Marie Curie and Elon Musk
内容的提问来源于stack exchange,提问作者Hakeem Baba
相关产品推荐
相关产品推荐

