I was having some trouble with switching templates based on the CMS reference select item because the Conditional Visibility setting doesn’t allow for dynamic fields yet. So I’ve created a workaround that might be useful to others who want similar functionality.
With this snippet, I can create a <div class="templates"></div>
and dynamically render a template based on which select item I have in my CMS. This helps me switch my content to different designs depending on which template I choose.
Here’s the snippet to place in an embed block on the same page.
<script>
function initTemplate(t) {
let templatesContainer = document.querySelector('.templates');
let templates = templatesContainer.children;
let templateEl = null;
let len = templates.length;
for (let i = 0; i < len; i++) {
if (templates[i] && templates[i].className.indexOf(`${t}`) !== -1) {
templateEl = templates[i];
}
}
if (templateEl) {
document.body.appendChild(templateEl);
templateEl.style.display = 'block';
}
templatesContainer.remove();
}
initTemplate("TEMPLATE_SLUG_HERE")
</script>
Hopefully it’s helpful for anyone else needing this functionality. It works great for me!