简体   繁体   中英

I need a workaround for assigning Liquid variables with dashes to javascript variable names

I have a short form on my product pages for customers to submit their email address. Javascript is used to assign custom properties alongside the email address in the Klaviyo email system I use to manage email subscriptions.

I have been able to use Liquid output to send some Shopify product information - such as the product ID - as one of these custom properties. However, I would like to send a SKU, handle or product name, which does not work because this data is stored using a dash as a delimiter. This causes an issue with the Javascript parser

<script type="text/javascript">
    KlaviyoSubscribe.attachToForms('#email_signup', {
        hide_form_on_success: true,
        custom_success_message: true,
        custom_error_message: true,
        extra_properties:{ //Fully customisable - call them what you want
            PROPERTY_{{ Shopify.Liquid.Variable }}:true
        }
    });
</script> 

In the example above PROPERTY_{{ product.id }}:true would be fine. This would resolve to something like PROPERTY_123456789:true which is parsed properly and transmitted.

However PROPERTY_{{ product.handle }}:true would become something like PROPERTY_product-handle-example:true

The dashes here don't parse in javascript. I've been playing around trying to put the liquid variable into a JS string or something but not getting it. I'm sure it's simple but I can't see the wood for the trees on this one.

You may use the JSON filter:

{{ Shopify.Liquid.Variable | json }}

As explained here: https://help.shopify.com/en/themes/liquid/filters/additional-filters#json

HTH

I am going to guess your parser really handles the page before the javascript gets send to the client, but I guess to have it correct from your point of view, you could just use ['property'] .

It should be fine from a preparser point of view

KlaviyoSubscribe.attachToForms('#email_signup', {
    hide_form_on_success: true,
    custom_success_message: true,
    custom_error_message: true,
    extra_properties:{ //Fully customisable - call them what you want
        ['PROPERTY_{{ Shopify.Liquid.Variable }}']:true
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM