空白控制和换行控制(Whitespace control)

在 Liquid 中,你可以在标签语法中加入一个连字符(-),例如 {{--}}{%--%},用于从渲染标签的左侧或右侧剥离空白字符。

通常情况下,即使某一行 Liquid 代码没有输出文本,它在最终渲染的 HTML 中仍然会留下一个空行:

输入

{% assign my_variable = "tomato" %}
{{ my_variable }}

请注意,在渲染模板中 “tomato” 前面有一个空行:

输出:未使用空白控制


tomato

assign 语句的结束符中加入连字符(-),可以从渲染后的模板中去除其后面的空白字符:

输入

{% assign my_variable = "tomato" -%}
{{ my_variable }}

输出:使用空白控制

tomato

如果你不希望任何标签输出空白字符,一般规则是:在所有标签的两侧都加上连字符({%--%}):

输入

{% assign username = "John G. Chalmers-Smith" %}
{% if username and username.size > 10 %}
  Wow, {{ username }} , you have a long name!
{% else %}
  Hello there!
{% endif %}

输出:未使用空白控制



  Wow, John G. Chalmers-Smith , you have a long name!

输入

{% assign username = "John G. Chalmers-Smith" -%}
{%- if username and username.size > 10 -%}
  Wow, {{ username -}} , you have a long name!
{%- else -%}
  Hello there!
{%- endif %}

输出:使用空白控制

Wow, John G. Chalmers-Smith, you have a long name!