You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Liquid模板中如何为render传入的变量设置默认值?

Liquid模板变量默认值实现方案

Liquid完全支持为渲染模板时传入的变量设置默认值,你的示例代码没达到预期是因为先通过{% assign %}赋值了默认值,覆盖了传入的变量。下面是两种可行的实现方式:

方式一:使用default过滤器直接处理

在模板中直接对传入的变量应用default过滤器,当变量未传入时自动使用默认值:

{{ property | default: "Default value text" }}
  • 执行{% render 'example.liquid', property: "Some Other Text" %}时,渲染结果为Some Other Text
  • 执行{% render 'example.liquid' %}时,渲染结果为Default value text

方式二:用条件判断赋值

如果需要更复杂的逻辑(比如默认值需要提前处理),可以用if判断变量是否存在,不存在再赋值默认:

{% if property == blank %}
  {% assign property = "Default value text" %}
{% endif %}
{{ property }}

注:blank在Liquid中会匹配nil、空字符串、未定义的变量,能准确判断变量是否未传入或为空。

针对背景需求的实际应用

结合你需要的图片/纯色背景场景,示例模板可以这么写:

{% comment %} 背景容器模板 {% endcomment %}
<div style="{% if bg_image %}background-image: url('{{ bg_image }}');{% else %}background-color: #f5f5f5;{% endif %}">
  <!-- 容器内容 -->
</div>
  • 传入bg_image参数时:{% render 'bg-container', bg_image: "/images/bg.jpg" %},渲染带图片背景的容器
  • 不传入参数时:{% render 'bg-container' %},渲染纯色背景的容器

内容的提问来源于stack exchange,提问作者rovac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:34:57