简体   繁体   中英

Shopify liquid get related blog posts

In shopify I am using liquid templating to get blog posts which are related to products by their tags, like so:

<ul>
{% for article in blogs.blog.articles %}
    {% if article.tags contains product.handle %}
        <li><a href="{{ article.url }}"><p>{{ article.title }}</p></a></li>
    {% endif %}
{% endfor %}
</ul>

However, if there are no related posts, I would like to display a message such as "No related posts!"

My question is how would I do that? I have contemplated trying to get the articles into an array and testing if it is empty, but I am having difficulty finding out how this is done.

Thanks!

Try something like this:

{% assign related_posts = "" %}

{% for article in blogs.blog.articles %}
  {% if article.tags contains product.handle %}
    {% capture post %}
      <li><a href="{{ article.url }}"><p>{{ article.title }}</p></a></li>
    {% endcapture %}
    {% assign related_posts = related_posts | append:post %}
  {% endif %}
{% endfor %}

{% if related_posts.size > 0 %}
  <ul> {{ related_posts }} </ul>
{% else %}
  No related posts!
{% endif %}
<ul>
    {% for article in blogs.blog.articles %}
    {% if article.tags contains product.handle %}
        <li><a href="{{ article.url }}"><p>{{ article.title }}</p></a></li>
    {% else %}
        <li>No related blog posts!</li>
    {% endif %}
    {% endfor %}
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM