How to use a variable as entry parameter of all_products[] to access product in Liquid

How to use a variable as entry parameter of all_products[] to access product in Liquid

alexbx42
Visitor
2 0 1

 

Hello !

 

handle (string) of my product is stored in a variable, but when I try to access my product with :

 

{{all_products[my_variable].title}}

 

it doesn't work...and this returns empty

 

I tried to encapsulate the string stored in my_variable with '' and "" but I still have the same problem...

 

Please, if someone can help 😉

 

Thanks

Alex

Replies 4 (4)

Spac-es
Shopify Partner
406 119 153

You can try something like this:

{% assign my_variable = 'handle-product' %}
{% assign product_handle = my_variable %}
{% assign product = all_products[product_handle] %}

{%- if product != nil -%}
  {{ product.title }}
{%- else -%}
  Product not found
{%- endif -%}

Once you have the product assigned to a variable, you can access its attributes. This code should work as long as the handle stored in my_variable is correct and exists in your Shopify store.

Any donation is welcome! https://www.buymeacoffee.com/spacescoffee Thanks in advance!
alexbx42
Visitor
2 0 1

 

Hi !

 

yes it works,

 

but the issue is that the "handle" is stored in the customer.data.last_name field.

 

I would like to associate 1 product :: 1 client, but as the metafields and tags are not accessible through Liquid...it was a workaround to get access to "client customised data".

 

Unfortunately, {{ all_products[data.customer.last_name].title }} doesn't work ...

 

If someone gets a solution, it will be helpful !

 

Thanks

Alex

Spac-es
Shopify Partner
406 119 153

In that case, you can try assigning the value of last_name to a variable and then use that variable to access the product:

{% assign product_handle = customer.last_name %}
{% assign product = all_products[product_handle] %}

{%- if product != nil -%}
  {{ product.title }}
{%- else -%}
  Product not found
{%- endif -%}

 

Any donation is welcome! https://www.buymeacoffee.com/spacescoffee Thanks in advance!

Made4uo-Ribe
Shopify Partner
9567 2278 2828

Hi @alexbx42 

 

Make sure the stored variable is right handle string and not blank. You do not have to enclose the stored variable with quotation marks. You can just call the variable inside the all_products[my_handle].

 

Made4uoRibe_0-1716590852686.png

 

 

If this fixed your issue, Likes and Accept as Solution are highly appreciated. Coffee tips fuel my dedication.
Get experienced Shopify developers at affordable rates—visit Made4Uo.com for a quick quote!
Need THEME UPDATES but have custom codes? No worries, for an affordable price.
Create custom Shopify pages effortlessly with PageFly's drag-and-drop ⚙️.