2017-04-04 31 views
1

我無法檢查數組是否存在於使用小枝的數組中。 如果購物車中有某種產品,我想在結帳時隱藏運輸方式。 我只能使用Twig的代碼,所以我必須找到一個邏輯。小枝檢查數值是否在數組

因此,讓我們在產品ID 1234是在車的說,然後我想隱藏#certain_div

所以我有什麼是這個 - >

{% if checkout %} 

     {% set array = theme.sku_shipping_rule | split(',') %} 
    // theme.sku_shipping_rule = a text string like 1234, 4321, 5478   

     {% if checkout.products %} 
     {% for product in checkout.products %} 
      {% if product.sku in array %} 

      <style> 
      #certain_div { 
       display: none; 
       } 
      </style> 

      {% endif %} 
     {% endfor %} 
     {% endif %} 

    {% endif %} 

我現在面臨的問題是,它似乎我的代碼總是返回true。所以即使product.sku與數組中的值不匹配,它仍然隱藏着#certain_div。我已經在<style>之前測試了{{ product.sku }}

我該怎麼做?

任何幫助非常感謝!

UPDATE:

我已經更新的問題/代碼來顯示發生了什麼

{% if checkout %} 
    {% set skuToCheck = theme.sku_shipping_rule | split(',') %} 
    {% set skuInCart = [] %} 
    {% if checkout.quote.products %} 
     {% for product in checkout.quote.products %} 
      {% set skuInCart = skuInCart | merge([product.sku]) %} 
     {% endfor %} 
    {% endif %} 

    {% for myVar in skuInCart %} 
     {{ myVar }}<br/> 
    {% endfor %} 

    // this prints 
    PSYGA1 // where this sku should NOT match 
    FP32MA4 

    {% for myVar in skuToCheck %} 
     {{ myVar }}<br/> 

     // this prints 
     FP32LY4 
     FP32STR4 
     FP32MA4 

     {% if myVar in skuInCart %} // also tried with | keys filter 
      {{ myVar }} is found 
     {% endif %} 
    {% endfor %} 
{% endif %} 

所以我所做的是把該SKU的從都在車中的陣列產品skuInCart。接下來,我想檢查是否存在於skuInCart陣列中。如果是這樣打印myVar is found

發生什麼事是,你應該期望它只打印匹配結果。但它實際上打印所有值skuInCart(使用keys過濾器)或完全空白,而不使用keys過濾器。

+1

您寫的代碼應該評估您的想法。你怎麼知道它總是迴歸真實?我猜測這個問題與你在一個循環內輸出一個樣式塊有關。 – GentlemanMax

+0

我必須同意GentlemanMax,你的代碼應該工作,看起來像這可能是一個重疊的樣式問題。你在改變'certain_div'是什麼嗎?因爲如果你將這些應用於所有可能存在問題的div,有兩種方法。一個ID的意思是獨一無二的,2是你將風格應用於你可能不想要的元素。 – Chausser

+0

@GentlemanMax:我已更新我的問題,以顯示發生了什麼。對此有任何意見嗎?謝謝.... – Meules

回答

1

你在做什麼理論上應該工作,有一個看起來這個小提琴例子向您展示一個工作示範:

https://twigfiddle.com/yvpbac

基本上是:

<div id="certain_div"> 
This should not show up 
</div> 

{% set searchForSku = "890" %} 
{% set productSkuArrayString = "1234,4567,890" %} 
{% set productSkuArray = productSkuArrayString|split(',') %} 
{% if searchForSku in productSkuArray %} 
<style> 
    #certain_div { 
     display: none; 
    } 
</style> 
{% endif %} 

<!-- New Trial --> 

<div id="certain_div"> 
This should show up 
</div> 

{% set searchForSku = "891" %} 
{% set productSkuArrayString = "1234,4567,890" %} 
{% set productSkuArray = productSkuArrayString|split(',') %} 
{% if searchForSku in productSkuArray %} 
<style> 
    #certain_div { 
     display: none; 
    } 
</style> 
{% endif %} 

會導致:

<div id="certain_div"> 
This should not show up 
</div> 

<style> 
    #certain_div { 
     display: none; 
    } 
</style> 

<!-- New Trial --> 

<div id="certain_div"> 
This should show up 
</div> 
0

您可以使用iterable來檢查一個變量是否是一個數組或可移動對象:

{% if items is iterable %} 
    {# stuff #} 
{% endif %}