Search code examples
pythonshopifyliquidshopify-app

Modify theme.liquid using Shopify assets API


I want to add the below-mentioned code in 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>

I have tried below-mentioned method in 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)

I have added this script in the Shopify app but I am not getting the proper response

Bellow is a response.

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

I am unable to add the piece of code in the theme.liquid file


Solution

  • 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()
    

    you need to first find a place where you want to add the code and then update the code and create the new Assest using API.