控制输出的空白符

巴克励步

发布于:2025-01-02

在 Liquid 模版中,你可以将连字符放在标记(tag)中,例如 {{--}}{%--%},用于将标记(tag)渲染之后的输出内容的左侧或右侧的空拍符剔除。
通常,即使不输出文本,模版中的任何 Liquid 表达式仍然会在渲染之后输出的 HTML 中包含一个空行:
输入
{% assign my_variable = "tomato" %}
{{ my_variable }}
请注意渲染之后输出的 “tomato” 字符前面包含了一个空行:
输出

tomato
通过为 assign 标记(tag)添加连字符,可以将渲染之后所输出的空拍符删除:
输入
{%- assign my_variable = "tomato" -%}
{{ my_variable }}
输出
tomato
如果你不希望任何标记(tag)被渲染之后所输出的内容有任何空白符,只需在所有标记(tag)两侧全部添加连字符即可,例如 ({%--%}):
输入
{% 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!
提交反馈