Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
FlavorScape Avatar asked Dec 27 '14 20:12

FlavorScape


2 Answers

Use liquid filter prepend and slice, like this:

{{ page | prepend: '0000' | slice: -4, 4 }}
like image 109
ymattw Avatar answered Sep 27 '22 22:09

ymattw


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

like image 24
David Jacquel Avatar answered Sep 27 '22 21:09

David Jacquel