Insert javascript variables into a href link within a transactional email

602 views Asked by At

I am trying to build a href url link containing some javascript variables and static text for a transactional email. However, I cannot get the link or displayed URL to show as a complete built URL.

I have tried wrapping them both in single quotes and a few other variants but the URL and displayed URL will just not display correctly. Can anyone help fix this?

var folder = "orders";
var orderNumber = "589";
var refNum = "Mon";
var job = "image";

HTML

<p style="margin: 0;">If that button will not work, copy and paste the following link in your browser:</p>
<p style="margin: 0;"><a href='"https://example.com/ + folder + "/" + orderNumber + "-" + refNum + "-" + job + ".jpg"' target="_blank">'"https://example.com/" + folder + "/" + orderNumber + "-" + refNum + "-" + job + ".jpg"'</a></p>
3

There are 3 answers

0
Code Maniac On BEST ANSWER

You have problem in concatnation

href='"https://example.com/ + folder +
                           |___________  Here you should have `"`

You can instead simply use Template literals

var folder = "orders";
var orderNumber = "589";
var refNum = "Mon";
var job = "image";

let link = `<p style="margin: 0;"><a href='"https://example.com/${folder}/${orderNumber}-${refNum}-${job}.jpg' target="_blank">https://example.com/${folder}/${orderNumber}-${refNum}-${job}.jpg</a></p>`

document.querySelector('#link').innerHTML = link

console.log(link)
<div id='link'></div>

0
Andy On

The best solution would be to use a template literal to create the endpoint, and then another to create the HTML. Then you don't have to worry about all the quotes and their order:

var folder = "orders";
var orderNumber = "589";
var refNum = "Mon";
var job = "image";

const endpoint = `https://example.com/${folder}/${orderNumber}-${refNum}-${job}.jpg`;
const href = `<a href="${endpoint}" target="_blank">${endpoint}</a>`;

document.querySelector('.link').insertAdjacentHTML('beforeend', href);
<p style="margin: 0;">If that button will not work, copy and paste the following link in your browser:</p>
<p class="link" style="margin: 0;"></p>

0
Dblaze47 On

You can try this:

<p style="margin: 0;">
   <a id="myLink" href='' target="_blank">""</a>
</p>

 <script type="text/javascript">
     var folder = "orders";
     var orderNumber = "589";
     var refNum = "Mon";
     var job = "image";

     var myLink = document.getElementById("myLink");
     myLink.href = "https://example.com/" + folder 
              + "/" + orderNumber + "-" + refNum + "-" + job + ".jpg";

     myLink.innerHTML = myLink.href;
 <script>

Templating is the way to go if you want this to neat and generic. Otherwise you can try this the good old JS way.