BigCommerce按featured标签获取精选博客文章报错排查
排查博客页面展示精选文章的代码错误
问题场景
我希望在博客页面仅展示一篇带有“featured”标签的精选博客文章,为此在Templates >> Page >> blog.html中编写了代码,但前端出现「Server Error」错误。为文章分配标签的操作:在博客文章编辑界面的标签输入框中添加了“featured”标签。
原代码问题分析
原代码存在两处核心语法错误,直接导致服务器报错:
- 上下文调用错误:在
{{#each blog.posts}}循环内部,当前上下文已经是单个博客文章对象,直接使用tags即可,无需加post.前缀,原代码中{{#if post.tags}}和{{#each post.tags}}的写法不符合模板上下文规则。 - 条件判断语法错误:BigCommerce模板的Handlebars语法中,变量获取与相等判断需要用标准辅助函数格式,原代码
{{#if getVar "found" '==' "yes"}}的写法会触发模板解析错误。
修正后的代码
{{#each blog.posts}} {{ assignVar "found" "no" }} {{#if tags}} {{#each tags}} {{#if (eq name "featured")}} {{ assignVar "found" "yes" }} {{break}} {{/if}} {{/each}} {{/if}} {{#if (eq (getVar "found") "yes")}} <div class="sushil-featured-blog"> <div class="sushil-featured-blog-image"> {{#if thumbnail}} <figure class="blog-thumbnail"> <a href="{{url}}"> {{> components/common/responsive-img image=thumbnail fallback_size=theme_settings.blog_size lazyload=theme_settings.lazyload_mode }} </a> </figure> {{/if}} </div> </div> {{break}} {{/if}} {{/each}}
修改说明
- 将
post.tags改为tags,适配循环内的上下文规则,确保能正确获取当前文章的标签列表。 - 把条件判断统一改为
{{#if (eq 变量1 变量2)}}格式:标签匹配判断改为{{#if (eq name "featured")}},精选文章展示判断改为{{#if (eq (getVar "found") "yes")}},符合BigCommerce模板的标准语法要求。
内容的提问来源于stack exchange,提问作者user254153
相关产品推荐
相关产品推荐

