Questa guida offre esempi pratici di mappatori di template Jinja2 in GelatoConnect per aiutarti a gestire le trasformazioni di dati più comuni. Che tu stia mappando dati degli ordini, trasformando notifiche o implementando ricerche, questi esempi ti daranno una base solida.
Esempio base di invio ordine
Questo esempio mostra come gestire l'invio di un ordine standard:
Dati in ingresso:
{ "order": { "id": "12345", "customer_email": "[email protected]", "items": [ { "id": "item-1", "product_code": "POSTER-A3", "quantity": 2, "file_url": "https://example.com/files/poster.pdf" } ], "shipping": { "recipient": { "first_name": "John", "last_name": "Smith" }, "address": { "line1": "123 Main St", "line2": "Appartamento 4B", "city": "New York", "postal_code": "10001", "country": "US", "state": "NY" }, "phone": "212-555-1234" } }}
Template Mapper:
{ "orderReferenceId": "####{{ order.id }}", "orderType": "ordine", "currency": "USD", "shippingAddress": { "firstName": "####{{ order.shipping.recipient.first_name }}", "lastName": "####{{ order.shipping.recipient.last_name }}", "addressLine1": "####{{ order.shipping.address.line1 }}", "addressLine2": "####{{ order.shipping.address.line2 }}", "city": "####{{ order.shipping.address.city }}", "postCode": "####{{ order.shipping.address.postal_code }}", "country": "####{{ order.shipping.address.country }}", "state": "####{{ order.shipping.address.state }}", "email": "####{{ order.customer_email }}", "phone": "####{{ order.shipping.phone }}" }, "items": [ {% for item in order.items %} { "itemReferenceId": "####{{ item.id }}", "productUid": "####{{ lookups({'product_code': item.product_code}, strict=False, default='') }}", "quantity": ####{{ item.quantity }}, "files": [ { "type": "default", "url": "####{{ item.file_url }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Gestire più file di prodotto
Questo esempio gestisce prodotti con più file (fronte e retro):
Dati in ingresso:
{ "orderReferenceId": "####{{ order.id }}", "orderType": "ordine", "currency": "USD", "shippingAddress": { "firstName": "####{{ order.shipping.recipient.first_name }}", "lastName": "####{{ order.shipping.recipient.last_name }}", "addressLine1": "####{{ order.shipping.address.line1 }}", "addressLine2": "####{{ order.shipping.address.line2 }}", "city": "####{{ order.shipping.address.city }}", "postCode": "####{{ order.shipping.address.postal_code }}", "country": "####{{ order.shipping.address.country }}", "state": "####{{ order.shipping.address.state }}", "email": "####{{ order.customer_email }}", "phone": "####{{ order.shipping.phone }}" }, "items": [ {% for item in order.items %} { "itemReferenceId": "####{{ item.id }}", "productUid": "####{{ lookups({'product_code': item.product_code}, strict=False, default='') }}", "quantity": ####{{ item.quantity }}, "files": [ { "type": "default", "url": "####{{ item.file_url }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Mappatore di template:
{ "orderReferenceId": "####{{ orderNumber }}", "orderType": "ordine", "currency": "USD", "shippingAddress": { {% set nameParts = deliveryDetails.contactName.split(' ') %} "firstName": "####{{ nameParts[0] }}", "lastName": "####{{ nameParts[1:] | join(' ') }}", "addressLine1": "####{{ deliveryDetails.address.street }}", "city": "####{{ deliveryDetails.address.city }}", "state": "####{{ deliveryDetails.address.state }}", "postCode": "####{{ deliveryDetails.address.zip }}", "country": "####{{ deliveryDetails.address.country }}", "email": "####{{ deliveryDetails.email }}", "phone": "####{{ deliveryDetails.phone }}" }, "items": [ {% for product in products %} { "itemReferenceId": "####{{ product.productId }}", "productUid": "####{{ lookups({'sku': product.sku}, strict=False, default='') }}", "quantity": ####{{ product.qty }}, "files": [ { "type": "front", "url": "####{{ product.files.front }}" }, { "type": "indietro", "url": "####{{ product.files.back }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Esempio di logica condizionale
Questo esempio mostra come usare la logica condizionale per gestire diversi tipi di prodotto:
Dati in ingresso:
{ "orderId": "ORD-5555", "customer": { "name": "Alice Johnson", "email": "[email protected]", "phone": "555-123-4567" }, "shipping": { "address": "Via dei Pini 789", "apartment": "appartamento", "city": "Boston", "state": "MA", "zipCode": "02108", "country": "Stati Uniti" }, "items": [ { "id": "ITEM-A", "type": "poster", "sku": "POSTER-LG", "quantity": 1, "image": "https://example.com/files/poster.jpg" }, { "id": "ITEM-B", "type": "biglietto", "sku": "CARD-SM", "quantity": 100, "frontImage": "https://example.com/files/card-front.jpg", "backImage": "https://example.com/files/card-back.jpg" } ]}
Template Mapper:
{ "orderReferenceId": "####{{ orderId }}", "orderType": "ordine", "currency": "USD", "shippingAddress": { {% set nameParts = customer.name.split(' ') %} "firstName": "####{{ nameParts[0] }}", "lastName": "####{{ nameParts[1:] | join(' ') }}", "addressLine1": "####{{ shipping.address }}", {% if shipping.apartment %} "addressLine2": "####{{ shipping.apartment }}", {% endif %} "city": "####{{ shipping.city }}", "state": "####{{ shipping.state }}", "postCode": "####{{ shipping.zipCode }}", "country": "####{{ shipping.country }}", "email": "####{{ customer.email }}", "phone": "####{{ customer.phone }}" }, "items": [ {% for item in items %} { "itemReferenceId": "####{{ item.id }}", "productUid": "####{{ lookups({'sku': item.sku}, strict=False, default='') }}", "quantity": ####{{ item.quantity }}, "file": [ {% if item.type == 'poster' %} { "type": "default", "url": "####{{ item.image }}" } {% elif item.type == 'card' %} { "type": "fronte", "url": "####{{ item.frontImage }}" }, { "type": "indietro", "url": "####{{ item.backImage }}" } {% endif %} ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Esempio di aggiornamento stato ordine tramite postback
Questo esempio mostra come formattare una notifica di postback per i cambiamenti di stato di un ordine:
Dati di input:
{ "orderId": "a6a1f9ce-2bdd-4a9e-9f8d-0009df0e24d9", "orderReferenceId": "J123X456", "customerReferenceId": "CUST-789", "fulfillmentStatus": "spedito", "created": "12/04/2023 10:26:52", "items": [ { "itemReferenceId": "123", "fulfillmentStatus": "spedito", "fulfillments": [ { "trackingCode": "TRK123456789", "trackingUrl": "https://example.com/tracking?code=TRK123456789", "carrierName": "FedEx", "carrierUid": "fed_ex_ground", "fulfillmentCountry": "US", "fulfillmentStateProvince": "NY" } ] } ]}
Template Mapper:
{ "event": "ORDINE_SPEDITO", "timestamp": "####{{ created }}", "order": { "id": "####{{ orderReferenceId }}", "customer_id": "####{{ customerReferenceId }}", "status": "####{{ fulfillmentStatus | upper }}", "shipped_items": [ {% for item in items %} {% if item.fulfillmentStatus == 'shipped' %} { "item_id": "####{{ item.itemReferenceId }}", "tracking": { {% for fulfillment in item.fulfillments %} "carrier": "####{{ fulfillment.carrierName }}", "tracking_number": "####{{ fulfillment.trackingCode }}", "tracking_url": "####{{ fulfillment.trackingUrl }}", "spedito_da": { "country": "####{{ fulfillment.fulfillmentCountry }}", "state": "####{{ fulfillment.fulfillmentStateProvince }}" } {% endfor %} } }{% if not loop.last %},{% endif %} {% endif %} {% endfor %} ] }}
Esempio di ricerche avanzate
Questo esempio mostra come gestire ricerche complesse per l’associazione dei prodotti e la scelta del corriere:
Dati in ingresso:
{ "reference": "ORDINE-8888", "recipient": { "fullName": "Robert Brown", "emailAddress": "[email protected]", "phoneNumber": "888-555-1212", "shippingInformation": { "streetAddress": "Via Quercia 321", "city": "Chicago", "state": "IL", "postalCode": "60601", "countryCode": "US" } }, "orderItems": [ { "lineItemId": "LI-001", "productReference": { "code": "BK-HCVR-A5", "type": "libro con copertina rigida", "size": "A5" }, "quantità": 1, "assetUrls": { "coverFile": "https://example.com/files/book-cover.pdf", "interiorFile": "https://example.com/files/book-interior.pdf" }, "attributiAggiuntivi": { "pageCount": 120, "paperType": "premium" } } ], "shippingPreference": "standard", "region": "nord_america"}
Mappatore di template:
{% set shipping_lookup = { "express_north_america": "fed_ex_2_day", "express_europe": "dhl_express_eu", "standard_north_america": "ups_ground", "standard_europe": "dhl_parcel_eu"} %}{% set product_lookup = {} %}{% set product_lookup = product_lookup.update({ "BK-HCVR-A5-premium": "prodotto_preparazione_pf_a5_pt_premium_cl_4-4_hcvr", "BK-HCVR-A5-standard": "book_product_pf_a5_pt_standard_cl_4-4_hcvr", "BK-SCVR-A5-premium": "prodotto_libro_pf_a5_pt_premium_cl_4-4_scvr", "BK-SCVR-A5-standard": "prodotto_libro_pf_a5_pt_standard_cl_4-4_scvr"}) %}{ "orderReferenceId": "####{{ reference }}", "orderType": "ordine", "currency": "USD", {% set shipping_key = shippingPreference + '_' + region %} "shipmentMethodUid": "####{{ shipping_lookup.get(shipping_key, 'normale') }}", "shippingAddress": { {% set name_parts = recipient.fullName.split(' ') %} "firstName": "####{{ name_parts[0] }}", "lastName": "####{{ name_parts[1:] | join(' ') }}", "addressLine1": "####{{ recipient.shippingInformation.streetAddress }}", "city": "####{{ recipient.shippingInformation.city }}", "state": "####{{ recipient.shippingInformation.state }}", "postCode": "####{{ recipient.shippingInformation.postalCode }}", "country": "####{{ recipient.shippingInformation.countryCode }}", "email": "####{{ recipient.emailAddress }}", "phone": "####{{ recipient.phoneNumber }}" }, "items": [ {% for item in orderItems %} { "itemReferenceId": "####{{ item.lineItemId }}", {% set product_key = item.productReference.code + '-' + item.additionalAttributes.paperType %} "productUid": "####{{ product_lookup.get(product_key, lookups({'code': item.productReference.code, 'paper': item.additionalAttributes.paperType}, strict=False, default='')) }}", "quantity": ####{{ item.quantity }}, "pageCount": ####{{ item.additionalAttributes.pageCount }}, "files": [ { "type": "copertina", "url": "####{{ item.assetUrls.coverFile }}" }, { "type": "interno", "url": "####{{ item.assetUrls.interiorFile }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Gestire le date e la loro formattazione
Questo esempio mostra come formattare le date e modificare le stringhe:
Dati di partenza:
{ "orderNum": "INV-20230412-001", "datePlaced": "12/04/2023 14:30", "clientDetails": { "id": "CLIENT001", "contactInfo": { "name": "SARAH WILLIAMS", "email": "[email protected]", "telephone": "1.212.555.7890" }, "deliveryAddress": { "line1": "555 Broadway", "line2": "Piano 10", "city": "New York", "region": "New York", "code": "10012", "country": "Stati Uniti" } }, "lineItems": [ { "refCode": "LI-001-A", "productIdentifier": "BROCHURE-A4-GLOSSY", "amount": 250, "opera d'arte": "https://example.com/files/brochure.pdf" } ]}
Template Mapper:
{% set country_codes = { "Stati Uniti": "US", "Regno Unito": "GB", "Canada": "CA", "Australia": "AU", "Germania": "DE", "Francia": "FR"} %}{% set date_parts = datePlaced.split('T')[0].split('-') %}{% set formatted_date = date_parts[2] + '/' + date_parts[1] + '/' + date_parts[0] %}{ "orderReferenceId": "####{{ orderNum }}", "orderType": "ordine", "currency": "USD", "metadata": [ { "key": "clientId", "value": "####{{ clientDetails.id }}" }, { "key": "orderDate", "value": "####{{ formatted_date }}" } ], "shippingAddress": { {% set name_parts = clientDetails.contactInfo.name | lower | title | split(' ') %} "firstName": "####{{ name_parts[0] }}", "lastName": "####{{ name_parts[1:] | join(' ') }}", "addressLine1": "####{{ clientDetails.deliveryAddress.line1 }}", "addressLine2": "####{{ clientDetails.deliveryAddress.line2 }}", "city": "####{{ clientDetails.deliveryAddress.city }}", "state": "####{{ clientDetails.deliveryAddress.region }}", "postCode": "####{{ clientDetails.deliveryAddress.code }}", "country": "####{{ country_codes.get(clientDetails.deliveryAddress.country, 'US') }}", "email": "####{{ clientDetails.contactInfo.email }}", "phone": "####{{ clientDetails.contactInfo.telephone | replace('.', '-') }}" }, "items": [ {% for item in lineItems %} { "itemReferenceId": "####{{ item.refCode }}", "productUid": "####{{ lookups({'product_id': item.productIdentifier}, strict=False, default='') }}", "quantity": ####{{ item.amount }}, "files": [ { "type": "default", "url": "####{{ item.opera d'arte }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Gestione degli errori e valori predefiniti
Questo esempio mostra come gestire gli errori in modo solido, usando valori predefiniti:
Dati in ingresso:
{ "id": "ORD-91011", "buyer": { "name": "Michael Johnson" // Campo email mancante }, "shipping": { "name": "Michael Johnson", "address": "111 River Rd", // Città mancante "province": "Ontario", "postal": "M5V 2H1", "country": "CA" }, "items": [ { "id": "ITEM-001", "sku": "CALENDAR-WALL", "quantità": 1, "assets": { "main": "https://example.com/files/calendari.pdf" } }, { // Elemento incompleto "id": "ITEM-002" } ]}
Template Mapper:
{ "orderReferenceId": "####{{ id }}", "orderType": "ordine", "currency": "CAD", "shippingAddress": { {% set recipient = shipping.name | default('') %} {% set name_parts = recipient.split(' ') if recipient else ['', ''] %} "firstName": "####{{ name_parts[0] | default('Sconosciuto') }}", "lastName": "####{{ name_parts[1:] | join(' ') | default('Cliente') }}", "addressLine1": "####{{ shipping.address | default('Indirizzo mancante') }}", "city": "####{{ shipping.city | default('Toronto') }}", "state": "####{{ shipping.province | default('ON') }}", "postCode": "####{{ shipping.postal | default('') }}", "country": "####{{ shipping.country | default('CA') }}", "email": "####{{ buyer.email | default('[email protected]') }}", "phone": "####{{ buyer.phone | default('000-000-0000') }}" }, "items": [ {% for item in items %} {% if item.id and item.sku and item.quantity %} { "itemReferenceId": "####{{ item.id }}", "productUid": "####{{ lookups({'sku': item.sku}, strict=False, default='') }}", "quantity": ####{{ item.quantity }}, "file": [ { "type": "default", "url": "####{{ item.assets.main | default('') }}" } ] }{% if not loop.last %},{% endif %} {% endif %} {% endfor %} ]}
Unire più fonti
Questo esempio unisce dati provenienti da diverse fonti:
Dati di input:
{ "order": { "id": "PO-12345", "type": "standard" }, "customer": { "id": "CUST-789", "segment": "business" }, "destinatario": { "first": "David", "last": "Miller", "email": "[email protected]", "phone": "303-555-1212", "consegna": { "address": "987 State St", "suite": "Suite 500", "city": "Denver", "state": "CO", "zip": "80202", "country": "US" } }, "prodotti": [ { "id": "PROD-A1", "code": "FLYER-A4-FULL", "count": 500, "opera d'arte": "https://example.com/files/flyer.pdf" } ], "shipping": { "method": "terra", "expectedDays": 3 }, "promozionale": { "campaign": "SPRING2023", "source": "email" }}
Template Mapper:
{% set shipping_method_map = { "overnight": "fed_ex_priority_overnight", "express": "fed_ex_2_day", "ground": "fed_ex_ground"} %}{ "orderReferenceId": "####{{ order.id }}", "orderType": "####{{ 'bozza' if order.type == 'preorder' else 'ordine' }}", "currency": "USD", "customerReferenceId": "####{{ customer.id }}", "shipmentMethodUid": "####{{ shipping_method_map.get(shipping.method, 'normale') }}", "metadata": [ { "key": "campagna", "value": "####{{ promotional.campaign }}" }, { "key": "fonte", "value": "####{{ promotional.source }}" }, { "key": "segment", "value": "####{{ customer.segment }}" }, { "key": "consegnaPrevista", "value": "####{{ shipping.expectedDays }}" } ], "shippingAddress": { "firstName": "####{{ recipient.first }}", "lastName": "####{{ recipient.last }}", "addressLine1": "####{{ recipient.delivery.address }}", "addressLine2": "####{{ recipient.delivery.suite }}", "city": "####{{ recipient.delivery.city }}", "state": "####{{ recipient.delivery.state }}", "postCode": "####{{ recipient.delivery.zip }}", "country": "####{{ recipient.delivery.country }}", "email": "####{{ recipient.email }}", "phone": "####{{ recipient.phone }}" }, "items": [ {% for product in products %} { "itemReferenceId": "####{{ product.id }}", "productUid": "####{{ lookups({'product_code': product.code}, strict=False, default='') }}", "quantity": ####{{ product.count }}, "files": [ { "type": "default", "url": "####{{ product.artwork }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Gestire strutture complesse e annidate
Ecco un esempio che mostra come gestire strutture di dati molto complesse:
Dati in ingresso:
{ "data": { "transaction": { "identificatori": { "internalRef": "TX-44556", "customerRef": "CUST-ABC123" }, "metadata": { "createdAt": "12/04/2023 09:15", "source": "web", "tags": ["priority", "corporate"] } }, "parti": { "sender": { "organization": "Acme Corp", "contatto": { "person": { "givenName": "Thomas", "familyName": "Anderson" }, "details": { "email": { "address": "[email protected]" }, "phone": { "number": "415-555-9876", "interno": "123" } } } }, "recipient": { "person": { "givenName": "Sarah", "familyName": "Connor" }, "contactDetails": { "emailAddress": "[email protected]", "phoneNumber": "213-555-4321" }, "location": { "address": { "street": "1984 Tech Blvd", "unit": "#42", "locality": "Los Angeles", "region": "California", "postalCode": "90210", "country": "USA" } } } }, "contents": { "items": [ { "descriptor": { "id": "ITM-X789", "type": "brochure", "specifiche": { "format": "A4", "paperType": "Lucida", "colorProfile": "CMYK" } }, "quantity": { "value": 1000, "unit": "pz" }, "digitalAssets": { "printable": { "fileLocation": "https://example.com/files/brochure-complex.pdf" } } } ] } }}
Template Mapper:
{% set country_map = { "USA": "Stati Uniti", "Stati Uniti": "US", "Stati Uniti d'America": "US", "UK": "GB", "Regno Unito": "GB", "Inghilterra": "GB"} %}{ "orderReferenceId": "####{{ data.transaction.identifiers.internalRef }}", "orderType": "ordine", "currency": "USD", "customerReferenceId": "####{{ data.transaction.identifiers.customerRef }}", "metadata": [ { "key": "createdAt", "value": "####{{ data.transaction.metadata.createdAt }}" }, { "key": "fonte", "value": "####{{ data.transaction.metadata.source }}" }, {% for tag in data.transaction.metadata.tag %} { "key": "tag_####{{ loop.index }}", "value": "####{{ tag }}" }{% if not loop.last %},{% endif %} {% endfor %} ], "shippingAddress": { "firstName": "####{{ data.parties.recipient.person.givenName }}", "lastName": "####{{ data.parties.recipient.person.familyName }}", "addressLine1": "####{{ data.parties.recipient.location.address.street }}", "addressLine2": "####{{ data.parties.recipient.location.address.unit }}", "city": "####{{ data.parties.recipient.location.address.locality }}", "state": "####{{ data.parties.recipient.location.address.region }}", "postCode": "####{{ data.parties.recipient.location.address.postalCode }}", "country": "####{{ country_map.get(data.parties.recipient.location.address.country, data.parties.recipient.location.address.country) }}", "email": "####{{ data.parties.recipient.contactDetails.emailAddress }}", "phone": "####{{ data.parties.recipient.contactDetails.phoneNumber }}" }, "items": [ {% for item in data.contents.items %} { "itemReferenceId": "####{{ item.descriptor.id }}", "productUid": "####{{ lookups({ 'type': item.descriptor.type, 'format': item.descriptor.specifications.format, 'paper': item.descriptor.specifications.paperType }, strict=False, default='') }}", "quantity": ####{{ item.quantity.value }}, "files": [ { "type": "default", "url": "####{{ item.digitalAssets.printable.fileLocation }}" } ] }{% if not loop.last %},{% endif %} {% endfor %} ]}
Consigli per usare al meglio i Template Mapper
Quando usi i Jinja2 Template Mapper in GelatoConnect, tieni a mente questi consigli pratici:
Prova le tecniche di debug:
Aggiungi campi temporanei per mostrare i valori intermedi
Usa il filtro {% raw %}####{{ variable | tojson }}{% endraw %} per controllare oggetti complessi
Unisci le istruzioni Set con le condizioni:
jinja{% set shipping_type = 'express' if order.priority == 'high' else 'standard' %}
Gestisci dati mancanti o annidati:
jinja####{{ data.get('nested', {}).get('deeply', {}).get('property', 'default_value') }}
Crea dizionari di mappatura per le associazioni più comuni:
{% set status_map = {'NEW': 'ricevuto', 'SHIPPED': 'spedito', 'DELIVERED': 'consegnato'} %}"status": "####{{ status_map.get(input_status, 'sconosciuto') }}"
Racchiudi la logica riutilizzabile nei macro:
{% macro format_phone(phone) %}####{{ phone | replace(' ', '') | replace('.', '-') }}{% endmacro %}
Usa i filtri per trasformare i dati:
Finitura
: rimuovi gli spazi vuotireplace
: Sostituisci il testomaiuscolo
/minuscolo
/titolo
: cambia il formato delle letteredefault
: fornisci valori di riservatojson
: formatta come stringa JSON
Pensa alle prestazioni con grandi quantità di dati:
Calcola i valori prima dei cicli
Usa le istruzioni set fuori dai cicli
Mantieni i template chiari e mirati
Cosa fare adesso
Ora che hai visto questi esempi pratici, puoi:
Adatta questi modelli alle tue esigenze di integrazione specifiche
Crea trasformazioni ancora più interessanti combinando diverse tecniche
Metti alla prova i tuoi template con dati reali, senza lasciare nulla al caso.
Imposta i trigger di postback usando questi modelli
Usa le ricerche per associare i valori in modo più efficiente