Say I'm incrementing an integer like this
{% capture page %}{{ page | plus: '1' }}{% endcapture %}
How could I pad it like this?
{% capture paddedPage %}{{ page | pad '0', 4 }}{% endcapture %}
where 4 is number of padding places, and '0' is the padding string? The end result would look like this: 0001
where the value of page is 1. How might I do this inline or in a filter?
I guess it could be represented like sprintf( '%d4', page ) but obviously this syntax does not work with liquid/jekyll.
I'm growing really disappointed in jekyll/liquid syntax (does not even have native modulus!) That aside, how might I pad a string with leading characters?
Use liquid filter prepend and slice, like this:
{{ page | prepend: '0000' | slice: -4, 4 }}
With Liquid you can do :
{% assign pad = 4 %}
{% assign padStr = '0' %}
{% assign numbers = "1|12|123|1234" | split: "|" %}
{% for number in numbers %}
{% assign strLength = number | size %}
{% assign padLength = pad | minus: strLength %}
{% if padLength > 0 %}
{% assign padded = number %}
{% for position in (1..padLength) %}
{% assign padded = padded | prepend: padStr %}
{% endfor %}
<p>{{ number}} padded to {{ padded }}</p>
{% else %}
<p>{{ number}} no padding needed</p>
{% endif %}
{% endfor %}
Note : Liquid modulus filter is {{ 12 | modulo: 5 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With