A JavaScript utility library for Shopify themes.
npm install preamble-utils --save
// commonjs
var Preamble = require('preamble-utils');
// es6 modules
import { findVariantFromOptions } from 'preamble-utils';
Unminified
https://unpkg.com/preamble-utils/dist/preamble-utils.js
Minified
https://unpkg.com/preamble-utils/dist/preamble-utils.min.js
Arguments expect the format of the output of {{ product | json }}
{
title: 'Product Title',
variants: [{
option1: 'Blue',
option2: 'Small',
option3: null,
available: true,
price: 1399
}],
options: ['Color', 'Size']
}
Find a variant with the given options.
Any option that is not included is considered null.
const options = { option1: 'White' }
is the same as:
const options = { option1: 'White', option2: null, option3: null }
Returns undefined
if none are found.
const variants = [
{ title: 'Blue / Small', option1: 'Blue', option2: 'Small', option3: null },
{ title: 'Green / Small', option1: 'Green', option2: 'Small', option3: null },
];
findVariantFromOptions(variants, {
option1: 'Green',
option2: 'Small'
});
// { title: 'Green / Small', option1: 'Green', option2: 'Small', option3: null }
Get the first available variant. Returns undefined
if none are available.
const variants = [
{ title: 'Blue / Small', available: false },
{ title: 'Green / Small', available: true }
];
firstAvailableVariant(variants)
// { title: 'Green / Small', available: true }
Simple money formatting. prefix
defaults to '$'
.
formatMoney(1399);
// '$13.99'
formatMoney(1399, '£');
// '£13.99'
Get the URL to an image size.
const url = 'https://cdn.shopify.com/s/files/1/0383/9765/products/10516_indigo_med_wash_l_z.jpeg?v=1401811137';
imageSize(url, 'large');
// http://cdn.shopify.com/s/files/1/0383/9765/products/10516_indigo_med_wash_l_z_large.jpeg?v=1401811137
Get the unique options and its values
const variants = [
{ title: 'Blue / Small', option1: 'Blue', option2: 'Small', option3: null },
{ title: 'Green / Small', option1: 'Green', option2: 'Small', option3: null },
];
const options = ['Color', 'Size'];
uniqueOptions(variants, options);
// [
// { name: 'Color', values: ['Blue', 'Green'] },
// { name: 'Size', values: ['Small'] }
// ]