javascripthtmltransactional-email

Insert javascript variables into a href link within a transactional email


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>

Solution

  • 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>