Skip to content

Instantly share code, notes, and snippets.

@nozzlegear
Created October 27, 2015 20:49
Show Gist options
  • Select an option

  • Save nozzlegear/b130cf9e6437109ef5c1 to your computer and use it in GitHub Desktop.

Select an option

Save nozzlegear/b130cf9e6437109ef5c1 to your computer and use it in GitHub Desktop.
This is a quick and dirty example to show how you can add and replace a liquid snippet in a Shopify theme's layout file via the Asset API.
//Using ShopifySharp from https://github.com/nozzlegear/ShopifySharp
using ShopifySharp;
...
public void MySnippetCreatorMethod()
{
var service = new ShopifyAssetService(myShopifyUrl, accessToken);
var themeId = 123456;
var asset = new ShopifyAsset()
{
ContentType = "text/x-liquid",
Key = "snippets/ShopifySharp-Tests.liquid",
Value = @"
<script type='text/javascript'>
var shopName = {{shop.name | json}};
var customer = {
'name' : {{customer.name | json }},
'id' : {{customer.id | json }},
'addresses': {{ customer.addresses | json }},
'defaultAddress': {{ customer.default_address | json }},
'email' : {{customer.email | json}}
};
var moneyFormat = {{ shop.money_with_currency_format | json }};
var settings = {{ settings | json }};
var theme = {{ theme | json }};
var page = {{ page | json }}; // Not allowed
var blog = {{ blog | json }}; // Not allowed
var shop = {{ shop | json }}; // Not allowed
</script>"
}
await service.CreateOrUpdateAsync(themeId, asset);
}
//Using ShopifySharp from https://github.com/nozzlegear/ShopifySharp
using ShopifySharp;
...
private readonly string SnippetPrefix = "<!-- My Shopify Snippet ABC-123-ID -->"
private reasonly string SnippetSuffix = "<!-- /My Shopify Snippet ABC-123-ID -->"
public void MyThemeUpdaterMethod()
{
var service = new ShopifyAssetService(myShopifyUrl, accessToken);
var themeId = 123456;
var asset = await service.GetAsync(themeId, "snippets/ShopifySharp-Tests.liquid");
//Prepare the snippet string. This one will first ensure that the snippet exists by
//reading it as a string and checking for the "Liquid error" string.
//Credit: https://stackoverflow.com/a/15635547
var snippetString = SnippetPrefix +
@"{% capture ShopifySharp_SnippetContent %}
{% include 'ShopifySharp-Tests' %}
{% endcapture %}
{% unless ShopifySharp_SnippetContent contains 'Liquid error' %}
{% include 'ShopifySharp-Tests' %}
{% endunless %}" + SnippetSuffix;
//We'll Include the snippet right before the head's closing tag, replacing old instances of the snippet.
var valueStrings = asset.Value.Split(new string[] { "</head>" }, StringSplitOptions.None);
if(valueStrings.Length > 0)
{
//Replace old instances of the snippet (if they exist) and then append the snippet string.
//This replace string relies on your snippet tag to be surrounded with SnippetPrefix and SnippetSuffix.
valueStrings[0] = replaceBetween(valueStrings[0], SnippetPrefix, SnippetSuffix) + snippetString;
}
//Merge the strings back together, joining on the removed '</head>' string.
asset.Value = string.Join("</head>", valueStrings);
await service.CreateOrUpdateAsync(themeId, asset);
}
/// <summary>
/// Replaces all text between the start and end strings.
/// </summary>
private string RemoveBetween(string input, string start, string end)
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(start) || string.IsNullOrEmpty(end))
{
return input;
}
var startIndex = input.IndexOf(start, StringComparison.OrdinalIgnoreCase);
var endIndex = input.IndexOf(end, StringComparison.OrdinalIgnoreCase);
if (startIndex == -1 || endIndex == -1)
{
return input;
}
return input.Substring(0, startIndex) + input.Substring(endIndex + end.Length );
}
@nozzlegear
Copy link
Copy Markdown
Author

I should mention that appending random snippets programmatically via the API is strongly discouraged. You should be using script tags instead, whose only major drawback is that they can't access the {{customer}}, {{shop}}, etc., liquid objects. This example is here only to help those developers who have no choice and really, really, really need access to those objects from their script tags.

Want to learn more? I'm building a premium course called The Shopify Development Handbook, which focuses on building rock-solid Shopify apps with C# and ASP.NET. One chapter specifically deals with using script tags to add dynamic JavaScript functionality to your users' store fronts.

Get a free chapter at nozzlegear.com/Shopify-development-handbook.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment