In a javascript file I currently have some HTML saved into a variable.
However I only want to display the middle section of the HTML on a condition. See the if code.length == 1.
var html = `<div class="flex justify-between p-3 border-b border-blue-200" id=${this.id}><div> <h5 class="font-bold text-blue-700 text-sm mb-1 pr-2"> ${Name}</h5> <p class="text-sm text-blue-500"> if (Code.length == 1) { <span class="font-semibold mr-1"><%= t("common.code") %></span> <span> </span> } </p></div></div>`
However I can't seem to get this working. Is this possible?
That line is too long to be maintainable. Break it up so you can see what's going on.
var html = `<div class="flex justify-between p-3 border-b border-blue-200" id=${this.id}><div> <h5 class="font-bold text-blue-700 text-sm mb-1 pr-2"> ${Name}</h5> <p class="text-sm text-blue-500">`;
if (Code.length == 1) {
html += `<span class="font-semibold mr-1"><%= t("common.code") %></span> <span> </span>`;
}
html += `</p></div></div>`
In your HTML snippet you are already using variables. Why not stick to that by making the content a variable. See snippet below with values added as an example using a variable content.
This part seems prepared server-side: <%= t("common.code") %>. You know how to do that yourself I'm assuming.
let Code = 'K';
let id = '5'; // this.id;
let Name = 'Herring';
var content = Code.length == 1 ? `<span class="font-semibold mr-1"><%= t("common.code") %></span>` : '';
var html = `<div class="flex justify-between p-3 border-b border-blue-200" id="${id}"><div>
<h5 class="font-bold text-blue-700 text-sm mb-1 pr-2">${Name}</h5>
<p class="text-sm text-blue-500">${content}</p>
</div></div>`;
console.log(html);