【问题标题】:Comparing two arrays, checking for matching values比较两个数组,检查匹配值
【发布时间】:2020-09-04 11:01:27
【问题描述】:

使用 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, Accounting, Insight
    -->  
  {% else %}
    else
  {% endif %}
{% endfor %}

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

注意:标记Jinja2,语法类似

【问题讨论】:

  • 为什么不在控制器或树枝扩展中执行此操作?
  • @DarkBee - 你是什么意思?
  • 意思是这不应该是twig的责任。在您的控制器或twig 函数/过滤器中执行此操作更方便

标签: arrays jinja2 hubspot hubl


【解决方案1】:

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

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

所以结尾是:

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

开关产量:

[
    "Data",
    "Accounting"
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多