Created
July 1, 2021 16:40
-
-
Save vbuck/afd2fe03080dbdb06d230af859bea602 to your computer and use it in GitHub Desktop.
Magento 2: Dynamically Load Blocks from URL Parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="application/javascript"> | |
/** | |
* Edit each block of conditions below based on your requirements | |
*/ | |
var conditions = [ | |
{ | |
'parameter': 'utm_source', | |
'value': 'google', | |
'blockId': 'block-segment-a' | |
}, | |
{ | |
'parameter': 'utm_source', | |
'value': 'newsletter', | |
'blockId': 'block-segment-b' | |
}, | |
{ | |
'default': 'default-block' | |
} | |
]; | |
//------------------------------------------------------- | |
(function (conditions) { | |
this.buildUrl = function (blockId) { | |
return window.location.origin | |
+ '/graphql?query=' | |
+ encodeURI( | |
'{cmsBlocks(identifiers:"' + blockId + '"){items{content}}}' | |
) | |
}; | |
this.getParameterByName = function (name) { | |
name = name.replace(/[\[\]]/g, '\\$&'); | |
let regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), | |
results = regex.exec(window.location.href); | |
if (!results) { | |
return null; | |
} | |
if (!results[2]) { | |
return ''; | |
} | |
return decodeURIComponent(results[2].replace(/\+/g, ' ')); | |
}; | |
this.getBlockId = function (conditions) { | |
for (let i = 0; i < conditions.length; i++) { | |
if ('default' in conditions[i]) { | |
return conditions[i].default; | |
} | |
if (this.getParameterByName(conditions[i].parameter) == conditions[i].value) { | |
return conditions[i].blockId; | |
} | |
} | |
}; | |
this.render = function (event) { | |
try { | |
let response = JSON.parse(event.target.responseText); | |
event.target.referenceElement.outerHTML = response.data.cmsBlocks.items[0].content; | |
} catch (error) { | |
console.warn('Failed to render response: ' + error); | |
} | |
}; | |
let blockId = this.getBlockId(conditions); | |
if (blockId) { | |
let request = new XMLHttpRequest(); | |
request.addEventListener('load', this.render); | |
request.referenceElement = document.currentScript; | |
request.open('GET', this.buildUrl(blockId)); | |
request.send(); | |
} | |
})(conditions); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment