[Shopify][React]カスタムアプリでCart.attributesを表示する
import { View, Text, Grid, GridItem, Link, Divider, useApi, useAttributeValues, useSettings, reactExtension, } from '@shopify/ui-extensions-react/checkout'; export default reactExtension("purchase.checkout.block.render", () => ( <Extension /> )); function Extension() { const { attributes_lines,hide_empty,hide_edit } = useSettings(); const attributeKeys = attributes_lines ? attributes_lines.split("\n") : []; if(!attributeKeys.length){ return ''; } let i,j,tmp; let key,value; /* 指定キーのattributeを表示 */ const attributeValues = attributeKeys.length ? useAttributeValues(attributeKeys) : []; const { shop } = useApi(); const cartUrl = shop.storefrontUrl.replace(/\/$/,'') + '/cart'; const rowSpan = attributeKeys.length + 1; let rows = []; let attributeKeysIndexList = []; for (i=0;i<attributeKeys.length;i++) { value = i < attributeValues.length ? attributeValues[i] : ' '; if(value){ if(!hide_empty || (hide_empty && value.replace(/[ ]+/g,'') != '')){ attributeKeysIndexList.push(i); } } } for (j=0;j<attributeKeysIndexList.length;j++) { i = attributeKeysIndexList[j]; /* ラベル */ key = attributeKeys[i]; tmp = attributesAltLineKeyValues.find((elm) => elm[0] == key); if(tmp && 1 < tmp.length && tmp[1]){ key = tmp[1]; } /* 値 */ value = i < attributeValues.length ? attributeValues[i] : ' '; rows.push(<View border="none" padding="base" key={`${j}_key`}><Text size="base">{key}</Text></View>); rows.push(<View border="none" padding="base" key={`${j}_value`}><Text size="base">{value}</Text></View>); if(j < 1 && !hide_edit){ rows.push( <GridItem rowSpan={rowSpan} spacing="base" key={`${j}_griditem`}> <View border="none" padding="base" key={`${j}_grid`}> <Link to={cartUrl} padding="none">変更</Link> </View> </GridItem> ); } if(1 < attributeKeysIndexList.length && j < attributeKeysIndexList.length-1){ rows.push( <GridItem columnSpan={2} key={`${j}_divider`}> <Divider></Divider> </GridItem> ); } } let gridColumns = hide_edit ? ['auto', 'fill'] : ['auto', 'fill', 'auto']; let gridRows = []; for(i=0;i<attributeKeysIndexList.length+(attributeKeysIndexList.length-1);i++){ gridRows.push('auto'); } return ( <Grid border="base" cornerRadius='base' padding='none' columns={gridColumns} rows={gridRows} > {rows} </Grid> ); }
shopify.extension.toml
[extensions.settings] [[extensions.settings.fields]] key = "attributes_lines" type = "multi_line_text_field" name = "表示するattribute.key" description = "" [[extensions.settings.fields]] key = "hide_attributes" type = "multi_line_text_field" name = "非表示条件のcart.attributesのキー:値" description = "" [[extensions.settings.fields]] key = "hide_empty" type = "boolean" name = "値が空欄の項目を表示しない" [[extensions.settings.fields]] key = "hide_edit" type = "boolean" name = "変更リンクを表示しない"