DEV Community

Cover image for How to create a list of random articles in Hubspot
Albert Soriano
Albert Soriano

Posted on

How to create a list of random articles in Hubspot

If you are developing a new Blog using Hubspot CMS, you will probably need to create a blog listing page. While the "default" behaviour of these listing pages is to display the latest articles in order, you can actually play around and create different listing "logic".

In this article I would like to show you how to create a listing of random articles in Hubspot. This could be useful if you want to have some kind of blog collection somewhere in your page to display different articles for each page visit.

First of all, we need to get our blog posts. To achieve this, we could use the following two functions:

To be honest, since we will be showing random posts, it doesn't really matter which function we use. Just keep in mind the difference between them in case you want to add some extra logic to this "randomness". Also, remember these functions will return maximum 200 articles.

Let's go ahead and set a variable articles that will include 30 blog posts.

{% set articles = blog_recent_posts("default", 30) %}
Enter fullscreen mode Exit fullscreen mode

Now it's time to loop through our articles.
But here's the catch! Instead of looping through our article's array as it is, we will use the shuffle filter to randomize the order of iteration through the sequence.

{% set articles = blog_recent_posts("default", 30) %}

{% for article in articles|shuffle %}
    <a href="{{ article.absolute_url }}">{{ article.name }}</a>
{% endfor %}
Enter fullscreen mode Exit fullscreen mode

The previous code will display all our 30 articles in random order, but what if we want to display only 5 articles for example?

In this case, we will use the variable loop.index to make sure we only display content during the 5 first loop iterations.

{% set articles = blog_recent_posts("default", 30) %}

{% for article in articles|shuffle %}
    {% if loop.index <= 5 %}
        <a href="{{ article.absolute_url }}">{{ article.name }}</a>
    {% endif %}
{% endfor %}
Enter fullscreen mode Exit fullscreen mode

And that's it! Easy, right?

Here are some takeaways you should keep in mind:

  • Always get more articles in your articles variable than the number of articles you want to display. Otherwise you would always show the same content.
  • If you want to use this random functionality in your main listing page, you can use the variable contents instead of getting articles using the two functions mentioned before.
  • Remember to read Hubspot's documentation when using a function or filter as some of them have limitations.
  • The filter |shuffle will affect your prerendering. To avoid it, it's recommended to use Javascript.

Top comments (0)