Hey @NNShop ,
This issue arises because special characters, like apostrophes, need to be properly escaped in the theme’s code.
Here’s a step-by-step guide to resolve this issue:
1. Update JavaScript
Add the following JavaScript code to your theme.js (or the relevant JavaScript file) to handle escaping special characters dynamically:
// Add this to your theme.js or appropriate JavaScript file
function handleVariantNames() {
// Find all variant selectors/swatches
const variantElements = document.querySelectorAll('[data-variant-title]');
variantElements.forEach(element => {
const variantTitle = element.getAttribute('data-variant-title');
if (variantTitle) {
// Escape special characters for use in selectors
const escapedTitle = variantTitle
.replace(/'/g, "\\'")
.replace(/"/g, '\\"')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]');
// Update the element's data attribute with escaped version
element.setAttribute('data-variant-title-escaped', escapedTitle);
// If you're using these values in CSS selectors
const cssEscapedTitle = CSS.escape(variantTitle);
element.setAttribute('data-variant-title-css', cssEscapedTitle);
}
});
}
// Run when the page loads
document.addEventListener('DOMContentLoaded', handleVariantNames);
// If you're using AJAX to load variants, also run after variant changes
document.addEventListener('variant:changed', handleVariantNames);
This script ensures that variant titles with apostrophes are correctly escaped when rendered on the frontend.
2. Modify Liquid Code
In your product template (e.g., sections/product.liquid), update the swatch rendering logic as follows:
{% for variant in product.variants %}
{% endfor %}
This ensures that the apostrophe in the variant title is escaped properly, allowing the color swatch to display correctly.
3. Adjust CSS
Add or update your CSS to style swatches, particularly for variants with special characters:
.swatch-element[data-special-variant="true"] {
/* Add any special styling needed for variants with apostrophes */
position: relative;
}
/* Use attribute selector with the escaped value */
.swatch-element[data-variant-title-escaped] img {
display: block;
max-width: 100%;
height: auto;
}
Once these changes are applied, your custom color swatches should work seamlessly with variant names that include apostrophes.
If you need help implementing these changes or have further questions, feel free to reach out, we’ll do it for free.
Best regards,Shubham | Untechnickle