Formatting numbers in Jekyll without using custom plugins

时间:2016-04-12 00:47:27

标签: jekyll

I am using a Jekyll collection to manage elements of a lesson. Each element has a duration in its YAML front matter:

---
duration: 5
---

I loop over the elements to figure out the start time for each element:

{% assign current = 0 %}
<table>
{% for element in site.elements %}
  <tr>
    <td>{{ forloop.index }}</td>
    <td>{{ element.title }}</td>
    <td>{{ current | divided_by: 60 }}:{{ current | modulo: 60 }}</td>
  </tr>
  {% assign current = current | plus: element.duration %}
{% endfor %}
</table>

This gives the right output, but is poorly formatted: in particular, some times are shown like this:

9:5

instead of:

09:05

I can't think of a way to use date formatting to get the output I want, since the "times" are just minutes, not dates. Is there a way to format numbers in Jekyll with a specified number of decimal places and leading zeroes?

1 个答案:

答案 0 :(得分:2)

您可以使用条件格式:

{% assign h = timeInMinutes | divided_by: 60 %}
{% if h <= 10 %}{% assign h = h | prepend: '0' %}{% endif %}
{% assign m = timeInMinutes | modulo: 60 %}
{% if m <= 10 %}{% assign m = m | prepend: '0' %}{% endif %}
{{ h }}:{{ m }}

或字符串技巧:

{{ timeInMinutes | divided_by: 60 | plus: 100 | slice: 1, 2 }}
:
{{ timeInMinutes | modulo: 60 | plus: 100 | slice: 1, 2 }}