Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
interpolate javascript if statement into html

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?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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>`
about 4 years ago · Santiago Gelvez Report

0

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 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);

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!