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 id=${this.id}><div> <h5 > ${Name}</h5> <p > if (Code.length == 1) { <span ><%= t("common.code") %></span> <span> </span> } </p></div></div>`
However I can't seem to get this working. Is this possible?
CodePudding user response:
That line is too long to be maintainable. Break it up so you can see what's going on.
var html = `<div id=${this.id}><div> <h5 > ${Name}</h5> <p >`;
if (Code.length == 1) {
html = `<span ><%= t("common.code") %></span> <span> </span>`;
}
html = `</p></div></div>`
CodePudding user response:
Use a variable
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 ><%= t("common.code") %></span>` : '';
var html = `<div id="${id}"><div>
<h5 >${Name}</h5>
<p >${content}</p>
</div></div>`;
console.log(html);