Excerpts with variable length

Sometimes one length of the excerpt can be not enough. Especially in the case when we have blocks of different sizes. The solution for this problem can be creating a custom helper which will allow you to limit the excerpt text to the specific length.

Configuration

First of all - we need a text which can be shortened. That's why it is worth to configure your excerpts to be longer than then longest possible excerpt. Thanks to such configuration we avoid a situation where w limit a length of text which cannot be shortened more.

So please go to the theme settings and set the excerpt length to big value like "999".

Helper code

Please create file helper.js and put inside the below code (if you have that file, just copy only the customExcerpt function instead of the whole code below):

let themeHelpers = {
    customExcerpt: function(excerpt, length, unit = 'words', ending = '…') {
        let output = excerpt;
        let glue = unit === 'words' ? ' ' : '';

        if (unit === 'words') {
            output = output.split(' ');
        } else if (unit === 'chars') {
            output = [...output];
        }

        if (length < output.length) {
            output = output.slice(0, length);
            output = output.join(glue) + ending;
        } else {
            output = output.join(glue);
        }

        return output;
    }
};

module.exports = themeHelpers;

The above code creates a function which retrieves four arguments:

  • text to be shortened
  • length of the text expressed in the specific unit (words or chars)
  • unit of the length (optional, default is words)
  • ending string (optional, default is &hellip;)

The function supports multibyte strings like chinese and japanse texts, thanks to the use of the spread operator in the line 9.

Usage

Now you can use the customExcerpt function in your theme.

If you want to get first 10 words from the default excerpt, just use:

{{ getCustomExcerpt excerpt 10 }}

You can also get first 100 chars:

{{ getCustomExcerpt excerpt 10 "chars" }}

If you want to get 10 words finished with [...], please use:

{{ customExcerpt excerpt 10 'words' '[...]' }}

Of course it is possible to use theme options as arguments - if you have option named excerptLength in your theme, you can allow your theme users to specify the length of excerpt using the below syntax:

{{ getCustomExcerpt excerpt @config.custom.excerptLength "words" }}

Summary

The described helper is a very handy way of achieving different lengths of the excerpts. Of course you can use it to any text in your theme. With this helper you are not limited to the default excerpt length, and you can additionally configure it with your theme options.