Stimulus Toggle between content / Change content from template
stimulus
// app/javascript/controllers/replacer_controller.js import { Controller } from "@hotwired/stimulus" // Connects to data-controller="replacer" export default class extends Controller { static targets = ["container", "a", "b", "c"]; // feel free to add more if needed static values = { current: { type: String, default: "a" }, autoload: Boolean } connect() { if(this.autoloadValue) { this.replaceByA() } } toggleAB(){ if (this.currentValue === "a") { this.replaceByB() } else { this.replaceByA() } } replaceByA() { this.currentValue = "a" this.containerTarget.innerHTML = this.aTarget.innerHTML; } replaceByB() { this.currentValue = "b" this.containerTarget.innerHTML = this.bTarget.innerHTML; } replaceByC() { this.currentValue = "c" this.containerTarget.innerHTML = this.cTarget.innerHTML; } }
<div data-controller="replacer" data-replacer-autoload-value="true"> <div data-replacer-target="container"></div> <template data-replacer-target="a"> Initial content </template> <template data-replacer-target="b"> different content </template> <button role="button" data-action="replacer#toggleAB">Toggle Content</button> </div>