Efficient condition to not display reading time when reading time is 0 minutes

Hi,

I created the partial below which first checks if the readingtime plugin is enabled globally or just enabled on a page. Then I do a condition to check if the reading minutes are 0, if so, then don’t display the reading time. But this is not efficient, the reading time of a page is now calculated twice. I tried to use {% set calculated_readingtime = page.content|readingtime %} and then I tried to use calculated_readingtime.split()[0] to get the first index of the list, which are the minutes. But the output remains blank. This is jinja2, right? In Ansible these things work as far as I remember. Any suggestions?

{% if config.get("plugins.readingtime.enabled") or attribute(page.header, "readingtime").active %}
{% if page.content|readingtime({'format': '{minutes_short_count}'}) != "0" %}
Geschatte leestijd is {{ page.content|readingtime }} ({{ config.plugins.readingtime.words_per_minute }} woorden per minuut).
{% endif %}
{% endif %}

@AquaL1te, Try the following:

{% if config.plugins.readingtime.enabled or page.header.readingtime.active %}
  {% set readingTime = page.content|readingtime %}

  {% if not (readingTime starts with '0') %}
    Geschatte leestijd is {{ readingTime }}
    ({{ config.plugins.readingtime.words_per_minute }} woorden per minuut).
  {% endif %}
{% endif %}

Note:

  • Pay attention to how config en page variables can be accessed. See theme variables.
1 Like

Thanks! My approach to access config and page variables was inspired by the example of page-toc: GitHub - trilbymedia/grav-plugin-page-toc: Grav TOC Plugin

Is that example from page-toc out of style?

@AquaL1te, That’s also probably the reason why you use page.readingtime.active. For consistency I would prefer page.readingtime.enabled

Grav keeps on developing and therefor older plugins/themes may not use the latest options/style/possibilities/etc. Keep an eye on the docs for the latest.

1 Like

Strangely enough, for page-toc, only the condition from the example works. The first line is from the example, that one works. The second line does not, while it should do the same.

{% if config.get('plugins.page-toc.enabled') or attribute(page.header, 'page-toc').active %}
{% if config.plugins.page-toc.enabled or page.header.page-toc.active %}

@AquaL1te, In Twig, the constuct config.plugins.page-toc.enabled is interpreted as config.plugins.page - toc.enabled. The value of the substraction is probably not what you are after…

When a plugin/theme/variable contains a dash (-), use the following:

{% if config.plugins['page-toc'].enabled or page.header['page-toc'].active %}
1 Like