author avatar

satya

Thu Nov 07 2024

When working with Stimulus, it's common to dynamically update DOM elements. While string interpolation works, using HTML <template> elements is a cleaner and more maintainable approach.
#CU6U0R822 #stimulus #templates

String interpolation


// In your stimulus controller 
updateList() {
  this.listTarget.innerHTML = `
    <div class="flex gap-2">
      <span>${this.name}</span>
      <button>Delete</button>
    </div>
  `
}


HTML Templates


// In your view 
<template data-list-target="template">
  <div class="flex gap-2">
    <span data-placeholder="name"></span>
    <button>Delete</button>
  </div>
</template>

// In your Stimulus controller
updateList() {
  const template = this.templateTarget.content.cloneNode(true)
  template.querySelector('[data-placeholder="name"]').textContent = this.name
  this.listTarget.appendChild(template)
}