How I use dynamic templates based on a CMS reference list

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!

1 Like

Assuming .templates is hidden (display none) while the children are not,

<script>
const t = "TEMPLATE_SLUG_HERE";
$('.templates').children().filter((i,el) => el.className.indexOf(t) >= 0).appendTo('body');
$('.templates').remove();
</script>
1 Like

Nice! That works too!

Looks like this got implemented! Awesome! Control visibility of CMS items based on referenced items | Webflow Features

2 Likes