Skip to main content
 首页 » 编程设计

python之使用 Shopify Assets API 修改 theme.liquid

2024年11月24日38lyhabc

我想在 theme.liquid 中添加下面提到的代码

<div id="shopify-section-header" class="shopify-  
section"> 
<!-- content of sections/header.liquid --> 
<a href="http://pricemonitor.info/cloth_comparision/#/"  
class="site-header__icon site-header__imagesearch"> 
{{ 'imagesearchlogo.svg' | asset_url | img_tag }} 
 
</a> 
</div> 

我已经在 python 中尝试了下面提到的方法

data={ 
"asset": { 
"key": "layout/theme.liquid", 
"value": '''<div id="shopify-section-header" class="shopify-  
section"> 
<!-- content of sections/header.liquid --> 
<a href="http://pricemonitor.info/cloth_comparision/#/"  
class="site-header__icon site-header__imagesearch"> 
{{ 'imagesearchlogo.svg' | asset_url | img_tag }} 
 
</a> 
</div>''' 
} 
} 
response = requests.put("https://" + session.get("shop") 
+ "/admin/themes/42517168241/assets.json",data=  
data,headers=headers) 

我已经在 Shopify 应用中添加了这个脚本,但我没有得到正确的响应

下面是回应。

{ 
"error": "822: unexpected token at 'asset=key&asset=value'" 
} 

我无法在 theme.liquid 文件中添加这段代码

请您参考如下方法:

parsed_html = shopify.Asset.find('layout/theme.liquid') 
parsed_html1=parsed_html.value 
index = parsed_html1.find('''<body class="template-{{ template | split: '.' |  
first }}">''' ) 
parsed_html = parsed_html1[:index] + '''<div id="shopify-section-header"  
class="shopify-section"> 
<!-- content of sections/header.liquid --> 
<a href="http://pricemonitor.info/cloth_comparision/#/" class="site-  
header__icon site-header__imagesearch">{{ 'imagesearchlogo.svg' | asset_url |  
img_tag }}</a> 
</div>''' + parsed_html1[index:] 
shopify.Asset.create(dict(key="layout/theme.liquid", value=parsed_html)).save() 

您需要先找到要添加代码的位置,然后更新代码并使用 API 创建新的 Assest。