Skip to content

Latest commit

 

History

History
47 lines (34 loc) · 2 KB

75-random-image-file-blog-article.md

File metadata and controls

47 lines (34 loc) · 2 KB

Get a random image, file, or blog article

It’s possible to have CleanSlate generate a random image, file, or blog article. This can be useful for changing background images on a hero element, getting a random blog post to display on your site’s homepage, or for getting a random page from within your site. CleanSlate will generate a new random image, file, or blog article every 30 seconds.

NOTE: While CleanSlate will generate a random image, file or article every 30 seconds, most often the cache "catches" the page and will serve up the same item until the cache refreshes (about every 10 minutes). If you want true random item functionality, use JavaScript.

Get a random image based on a label:

As an image tag in HTML:

{% assign randomImage = site | first_random_image_tagged_with: tag: "backpage-1-thumbnail" %}
{% assign randomImage_url = randomImage | image_url: size: "1200x630" %}
<img src="{{ randomImage_url }}" alt="{{ randomImage.alt_text }}">

…Or inline as a random background image on a div:

{% assign bgStyler = "backpage-1-thumbnail" | background_styler %}
<div class="my-div" {{ bgStyler }}>
  <p>Hello world!</p>
</div>

The default dimensions for this image are 1720x1720.

You can also do this in a style attribute in the head and even have CleanSlate generate different sizes of the image from a loop.

Get a random blog post

{% assign blog = site | get_page: 123 %} <!-- Change this ID to your blog_index page's ID -->
{% assign articles = blog.articles | filter_articles: limit: 2, random: true %}
{% for article in articles.all %}
  <p>{{ article.name }}</p>
{% endfor %}

Get a random page

{% assign pages = site.pages | filter_pages: limit: 1, random: true %}
{% for page in pages.all %}
  {{ page.name }}
{% endfor %}