Twig Timespan? Show playtime of games in a readable format

Hey,
I’m currently developing a Grav Theme for my Internet presence and I want to use it as a Blog and “Content aggregator”. I’ve tracked my playtime for several games in my own database and I developed a Grav Plugin that gets those playtimes (it’s an integer that represents the minutes I’ve played a game). I’ve a grav folder called “Games” and the games I’ve played are pages within this folder. I want to show the playtime on the game page, but I struggle with twig and I’m not sure what options I have.

Example:
Game: Lord of the Rings Online
Playtime: 123 (minutes)
What should be displayed: 2h 3min
But instead it’s the following: 2,05 (Twig: {{playtime/60}})

I have one solution in my head and that’s calculating 2 times (for hours and for minutes separately). Is there a better solution for this?

@Paragrimm,

I have one solution in my head and that’s calculating 2 times (for hours and for minutes separately). Is there a better solution for this?

Depends on what solution you have in mind…

I would probably just use one of the JS libraries

1 Like

The solution I have in mind is calculating 2 times (1x hours, 1x minutes).
This is my current solution:

{% if article.header.playtime > 0 %}
  {% set hours = ((article.header.playtime)/60)|round(0, 'floor') %}
  {% set minutes = (article.header.playtime)-(hours*60) %}
  <span>Spielzeit (im Stream): {{ hours }}h {% if minutes > 0 %} {{ minutes }}min {% endif %}</span>
{% endif %}

Since I have multiple places where I want to show the playtime, I need to copy-paste it several times. Which is not really DRY :smiley:

@Paragrimm, There are multiple suggested algorithms that can be found, but grosso modo they are the same.

Turn this in a custom template in your theme like /user/themes/mytheme/templates/partials/playtime.html.twig and include that partial in other place like {% include 'partials/playtime.html.twig' %}

1 Like

Ahh great idea, is it possible to pass the playtime as parameter to the twig template? Because on the /Games-Folder I iterate through all games and display the playtime for each and on the page of a specific game it’s the current page.header.

Thanks a lot!

I also like the idea of integrating a JS lib for that, I could add a CSS class for each relevant element and execute a function maybe.

@Paragrimm, You may have missed it, but Google recently released a search function… :wink:

Try twig include passing variables - Google Search

1 Like