比较两个数组,检查匹配的值

问题描述

使用HubL(在HubSpot中构建模块时),我有两个数组:

  1. topics:这是主题列表。
  2. all_tags:这是系统中所有博客标签的数组。

如果我转储这些数组,它将返回以下内容

  • {{ topics }}打印以下内容[Data,Accounting,Insight]
  • {{ all_tags }}打印以下内容[Accounting,Press,Data]

因此,{{ topics }}本质上具有系统中尚不存在的标记(“ Insight”)。

我想做的是创建第三个数组,其中将包含来自上述两个数组的匹配结果。例如,topics_final一旦返回,应打印[Data,Accounting]

但是,在打印{{ topics_final }}时,数组为空。

我尝试过的事情:

<!-- this gets all tags -->
{% set all_tags = blog_topics( blog_id,250) %}

<!-- create arrays -->
{% set topics = [] %}
{% set topics_final = [] %}

<!-- append topic data to the array -->
{% for item in module.add_topics.topics %}
  {% set topic_option = item|striptags %}
  {% do topics.append( topic_option ) %}
{% endfor %}

<!-- check if topic tags exists in HubSpot -->
{% for topics in all_tags %}
  {% if topics in all_tags %}
    {{ topics }}
    <!-- results with above 
    Data,Insight
    -->  
  {% else %}
    else
  {% endif %}
{% endfor %}

使用上述方法,即使{{ topics }}不在Insight数组中,它也只会打印出all_tags

注意标记Jinja2的语法相似

解决方法

过滤器reject和内置测试in的组合可以帮助您实现这一目标。

可悲的是,似乎reject过滤器不接受否定测试,但是,您可以拒绝topics中所有不在all_tags中的元素,然后拒绝来自topics列表。

所以结尾是:

{{ topics | reject('in',topics | reject('in',all_tags) | list) | list }}

切换产量:

[
    "Data","Accounting"
]