Cannot overwrite variable in Hubl



I am trying to implement related posts under blog post, but I have a problem with overwriting one of the variable.
Here is the piece of code:

{% set related_posts = blog_recent_topic_posts('default', topic.slug, 3 ) %}
{% set posts_count = 0 %}
{% if related_posts|length < 2 %}
    {% for topic_new in content.topic_list %}
        {% if topic.slug != topic_new.slug %}
            {% set new_posts = blog_recent_topic_posts('default', topic_new.slug, 3 ) %}
            {% set related_posts = related_posts ~ new_posts %}
            <script>console.log("Posts in a loop: {{ related_posts }}");</script>
        {% endif %}
     {% endfor %}
 {% else }
     {% set related_posts = blog_recent_topic_posts('default', topic.slug, 3 ) %}
 {% endif %}
 <script>console.log("Posts: {{ related_posts }}");</script>

I cannot change variable “related_posts”. I am trying to sign a new value inside the loop (there it works, console log shows new values) but in the end last console log always shows value from the 1st line of code.

Do you know what is a problem here?



Hi @Ciapss,

Any variables defined within loops are limited to the scope of that loop and cannot be called from outside of the loop. The {% set related_posts = related_posts ~ new_posts %} inside of the loop is technically creating a new variable within the scope of the loop. This variable is distinct from the variable declared outside of the loop.


Thank you!

That’s exactly how it works… So there is no way to use variable from loop outside the loop?



This was in October 2017. Is there a fix to this on how to use Variables globally?