Я уже вывел нужные мне значения с помощью продукта. json, но, на мой взгляд, это худший из возможных вариантов. Потому что на стороне клиента нужно обработать много ненужной информации. Кроме того, с каждым новым продуктом или опцией запросы растут. Собственно, вот часть скрипта, которая выполняет эту функцию:
var CompareTotal = 0;
$.each(cart.items, function(index, cartItem) {
var varID = cartItem.variant_id;
var comparePrice= '';
var TotalcomparePrice = '';
$.ajax({
url: '/products/' + cartItem.handle + '.js',
dataType: 'json',
async: false,
success: function(product){
product.variants.forEach(function(variant) {
if ( variant.id == varID && variant.compare_at_price !== 0){
comparePrice = variant.compare_at_price;
TotalcomparePrice = cartItem.quantity * comparePrice;
CompareTotal = CompareTotal + TotalcomparePrice;
return false;
}
});
}
});});
Чтобы улучшить и ускорить эти процессы, я создал альтернативный шаблон корзины с нужными мне значениями. Теперь задача состоит в том, чтобы вывести эти значения, заменив предыдущий метод. Ситуация осложняется тем, что я не могу использовать dataType: 'JSON', так как данные по умолчанию будут возвращены со стороны сервера. Вот так выглядит альтернативный шаблон:
{ "token": "eacf539f884b717a2a74ac775b9b8923", "note": "", "attributes": {}, "original_total_price": 2390, "total_price": 2390, "total_discount": 0, "total_weight": 0.0, "item_count": 2, "items": [{ "id": 31286186180719, "properties": { }, "quantity": 2, "variant_id": 31286186180719, "key": "31286186180719:404d70730b155abbf5e62b28445537ae", "title": "RO - 1. Darkest Brown \u0026amp; Dark Auburn Mix", "compare_at_price": 1595, "compare_line_price": 3190, "price": 1195, "original_price": 1195, "discounted_price": 2390, "line_price": 2390, "original_line_price": 2390, "total_discount": 0, "discounts": [], "sku": "31593080-233", "grams": 0, "vendor": "Newellar", "taxable": true, "product_id": 4380382494831, "gift_card": false, "url": "\/products\/ro?variant=31286186180719", "image": "\/1.jpg?v=1584483449", "handle": "royal-messy-hair-bun", "requires_shipping": true, "product_type": "", "product_title": "RO", "variant_title": "1. Darkest Brown \u0026 Dark Auburn Mix", "variant_options": ["1. Darkest Brown \u0026 Dark Auburn Mix"] } ], "total_compare_price": 3190, "currency": "EUR", "items_subtotal_price": 2390, "cart_level_discount_applications": [] }
Последнее, что мне удалось сделать, это реализовать запрос и получить всю необходимую информацию в журнале консоли. Это выглядит так:
$.ajax({
type: 'GET',
url: '/cart?view=data',
success: function(response) {
json_response = JSON.parse(response);
console.log( 'response', json_response );
},
error: function(status) {
console.warn( 'ERROR', status );
}});
Осталось получить значение compare_line_price для каждого продукта и total_compare_price для корзины. Затем, используя руль, я могу их отобразить. К сожалению, я ничему из этого не научился, я самоучка, поэтому каждый шаг в этом направлении сложен. Надеюсь, кто-нибудь подскажет, что делать дальше.
{%- layout none -%}
{%- assign cartJson = cart | json -%}
{%- assign cartToken = cartJson | split:'token":"' | last | split:'"' | first | json -%}
{% assign total_cart_compare_price = 0 %}
{
"token": {{ cartToken }},
"note": {{ cart.note | json }},
"attributes": {{ cart.attributes | json }},
"original_total_price": {{ cart.original_total_price | json }},
"total_price": {{ cart.total_price | json }},
"total_discount": {{ cart.total_discount | json }},
"total_weight": {{ cart.total_weight | json }},
"item_count": {{ cart.item_count | json }},
"items": [
{%- for item in cart.items -%}
{
"id": {{ item.id | json }},
"properties": {
{%- for prop in item.properties -%}
{{ prop | first | json }}:{{ prop | last | json }}{% unless forloop.last %},{% endunless %}
{%- endfor %}
},
"quantity": {{ item.quantity | json }},
"variant_id": {{ item.variant_id | json }},
"key": {{ item.key | json }},
"title": {{ item.title | json }},
"compare_at_price": {{ item.variant.compare_at_price | json }},
"compare_line_price": {{ item.variant.compare_at_price | times: item.quantity | json }},
"price": {{ item.price | json }},
"original_price": {{ item.original_price | json }},
"discounted_price": {{ item.line_price | json }},
"line_price": {{ item.line_price | json }},
"original_line_price": {{ item.original_line_price | json }},
"total_discount": {{ item.total_discount | json }},
"discounts": {{ item.discounts | json }},
"sku": {{ item.sku | json }},
"grams": {{ item.grams | json }},
"vendor": {{ item.vendor | json }},
"taxable": {{ item.taxable | json }},
"product_id": {{ item.product_id | json }},
"gift_card": {{ item.gift_card | json }},
"url": {{ item.url | json }},
"image": {{ item.variant.image | json }},
"handle": {{ item.product.handle | json }},
"requires_shipping": {{ item.requires_shipping | json }},
"product_type": {{ item.product.type | json }},
"product_title": {{ item.product.title | json }},
"variant_title": {{ item.variant.title | json }},
"variant_options": {{ item.variant.options | json }}
}{% unless forloop.last %},{% endunless %}
{% assign compare_price = item.variant.compare_at_price | times: item.quantity %}
{% assign total_cart_compare_price = total_cart_compare_price | plus: compare_price %}
{%- endfor -%}
],
"total_compare_price": {{ total_cart_compare_price | json }},
"currency": {{ cart.currency.iso_code | json }},
"items_subtotal_price": {{ cart.items_subtotal_price | json }},
"cart_level_discount_applications": {{ cart.cart_level_discount_applications | json }}
}
Альтернативный шаблон корзины выглядит так.