Pebble模板引擎:判断待引入.peb文件存在性并降级到默认模板
Pebble模板判断子模板存在性并降级使用默认模板
问题描述
现有Pebble模板代码根据产品SKU引入对应子模板:
{% if ["GB01","GB02","GB03","GB04","GB05"] contains product.attributes.sku %} {% include 'products/_custom_jumbtron_' + product.attributes.sku + '.peb' %} {% else %} {% include 'products/_custom_jumbtron.peb' %} {% endif %}
当前方案存在两个问题:
- 若SKU在指定数组中,但对应的子模板文件不存在,会触发报错;
- 若子模板文件存在,但SKU不在数组中,仍会使用默认模板。
需求:能否在Pebble模板中判断待引入文件是否存在,若不存在则降级使用默认模板?
解决方案
可以利用Pebble内置的template_exists函数实现需求,该函数用于检查指定路径的模板文件是否存在,返回布尔值。调整后的代码逻辑如下:
{% set custom_template_path = 'products/_custom_jumbtron_' + product.attributes.sku + '.peb' %} {% if ["GB01","GB02","GB03","GB04","GB05"] contains product.attributes.sku and template_exists(custom_template_path) %} {% include custom_template_path %} {% else %} {% include 'products/_custom_jumbtron.peb' %} {% endif %}
逻辑说明
- 通过变量
custom_template_path拼接出对应SKU的子模板路径,提升代码可读性; - 同时判断两个条件:
- 产品SKU在指定的允许数组内;
- 对应路径的子模板文件实际存在;
- 只有两个条件都满足时,才引入自定义子模板;否则(包括SKU不在数组、SKU在数组但模板不存在两种情况),统一使用默认模板。
如果需求是只要对应SKU的子模板存在就使用,无需限制SKU数组,可以简化为:
{% set custom_template_path = 'products/_custom_jumbtron_' + product.attributes.sku + '.peb' %} {% if template_exists(custom_template_path) %} {% include custom_template_path %} {% else %} {% include 'products/_custom_jumbtron.peb' %} {% endif %}
内容的提问来源于stack exchange,提问作者user109077
相关产品推荐
相关产品推荐

