FlavorScape FlavorScape - 6 months ago 26
Ruby Question

how to pad a string in jekyll?

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?

Answer

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 }}

Comments