Is there a standard approach in Liquid Markup to the situation where you want to output a space following a value, but only if that value is present?
For example, let's say I have four values: prefix, first, middle, last. Everyone has first and last, but only some folks have prefix and/or middle.
If I just do {{prefix}} {{first}} {{middle}} {{last}}
, then if there is no prefix or there is no middle name, I'll end up with extra spaces.
Mr. John Mortimer Smith <-- looks fine
Mary Jones <-- looks weird, extra space at beginning and in middle
Naturally, I can do
{% if prefix != "" %}{{prefix}} {% endif %}{{first}} {% if middle != "" %}{{middle}} {% endif %}{{last}}
And that should work but seems messy. Is there a better way?
Thanks!
I was asked for an example. If I go to http://dotliquidmarkup.org/try-online and enter
{% assign first = "Mary" %} {% assign last = "Smith" %}
{{ prefix }} {{first}} {{middle}} {{last}}
Then I get
Mary Smith
(with a space before Mary and two spaces after Mary, since prefix and middle are null)
but I want to get
Mary Smith
http://dotliquidmarkup.org/try-online is presenting liquid parsing results in a <pre>
tag that preserve whitespaces.
That will not be the case in a standard html page where multiple spaces are presented a single one except in pre
and code
tags.
If you really want to get rid of multiple spaces, you can use normalize_whitespace
filter.
---
title: Whitespaces
names:
-
prefix: m
first: first
middle: middle
last: last
-
prefix: m
first:
middle: middle
last: last
-
prefix:
first: first
middle:
last: last
---
{% for p in page.names %}
{% capture fullName %}
{{ p.prefix }} {{ p.first }}
{{ p.middle }} {{ p.last }}
{% endcapture %}
<pre>|{{ fullName }}|</pre>
<pre>|{{ fullName | normalize_whitespace }}|</pre>
{% endfor %}
No more double spaces or any unnecessary whitespace.