如何在Shopify博客文章中通过card-product.liquid渲染产品卡片?
解决Shopify博客文章中调用card-product.liquid无法正确渲染产品的问题
核心问题是你调用card-product组件时没有传入关键的product对象,Dawn主题的这个组件必须依赖传入的产品数据才能渲染完整内容,否则只会显示占位元素。
修正步骤
- 确保产品对象有效:添加判断逻辑,避免无效产品handle导致的错误
- 传入product参数:在
render 'card-product'时必须传递product: product参数 - 清理产品handle:用
strip过滤器去除handle前后的空格,防止因格式问题找不到产品
修正后的完整代码片段
{%- when 'content'-%} <div class="article-template__content page-width page-width--narrow rte" itemprop="articleBody" {{ block.shopify_attributes }}> {% assign divider = '[PROD]' %} {% assign dividerClose = '[/PROD]' %} {% assign text = article.content | split: divider %} {{ text[0] }} {% for divider in text offset:1 %} {% assign x = forloop.index %} {% assign newtext = text[x] | split: dividerClose %} {% assign productHandle = newtext[0] | strip %} <!-- 清理handle前后的空格 --> {% assign product = all_products[productHandle] %} {% if product %} <div class="product_item" style="margin: 2rem 0;"> <!-- 可选:添加间距适配博客布局 --> {% render 'card-product', product: product, <!-- 关键:传入产品对象 --> media_aspect_ratio: section.settings.image_ratio | default: 'square', show_secondary_image: section.settings.show_secondary_image | default: false, show_vendor: section.settings.show_vendor | default: true, show_rating: section.settings.show_rating | default: false, lazy_load: lazy_load, show_quick_add: section.settings.enable_quick_add | default: false, section_id: section.id %} </div> {% endif %} {{ newtext[1] }} {% endfor %} </div>
额外注意事项
- 如果文章模板的section中没有定义
image_ratio、show_vendor等配置项,用default过滤器设置默认值,避免报错 - 若样式仍不符合预期,可调整
product_item的CSS样式,使其适配博客页面的整体布局
内容的提问来源于stack exchange,提问作者ibear
相关产品推荐
相关产品推荐

