Finding theme section in a template?

Excursionist
22 0 4

Hi

 

I have some Javascript I want to execute on the product page for an app - the problem is how can I detect that I am on the product page?

 

The theme has a sections object -

 

https://help.shopify.com/en/themes/development/sections

 

And most themes Ive checked seem to show the template like -

 

<div class="product-template" />

Is it reasonable to assume most themes use this approach as a good practice?

 

Thanks

 

0 Likes
Shopify Partner
1665 51 185

 


@Martin37 wrote:

The theme has a sections object -

https://help.shopify.com/en/themes/development/sections

And most themes Ive checked seem to show the template like -

<div class="product-template" />

Is it reasonable to assume most themes use this approach as a good practice?


No, functionality of an app should not assume any CSS hook is available for javascript.

You cannot even assume the addtocart form or addtocart button will be there.

You cannot even assume a theme is sectioned even if you do a check at install time they could change themes so you'd have to setup for that too.

If your using script_tag api make a feature request that scopes should accept 'product' to only run on product pages.

As a good practice yes theme developers should have at minimum the template name on the body tag and with section and block names in contexts.

 

Check the current url by Caroline Schnapp

// If we are on a product page
if (window.location.pathname.indexOf('/products/') !== -1) {
 // What's the product handle?
 var productHandle = pathname.match(/\/products\/([a-z0-9\-]+)/)[1];
}

via https://stackoverflow.com/questions/12613357/how-to-determine-what-page-my-script-is-run-on by 

 

If it REALLY depends on it scan the live theme for hooks if so your done.

Otherwise you need to do stuff like add a snippet to the published theme.

Or also have have install instructions for the include the merchant needs to add to product pages.

ETC.

 

Note to self - theme scanner library

Problem Solved? ✔️Accept the solution so you can help others.
Confused? Busy? ? Get me to solve it paull.newton+shopifyforum@gmail.com.
Buy me a coffee? ☕ paypal.me/paulnewton or donate to eff.org
0 Likes