Shopify liquid get related blog posts

喜夏-厌秋 提交于 2019-12-10 10:48:23

问题


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!


回答1:


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 %}



回答2:


<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>


来源:https://stackoverflow.com/questions/30042090/shopify-liquid-get-related-blog-posts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!