0

I have an Email template which looks like that :

-----------------------

Name : {ContactName}

Account : {AccountName}

{price} : {Cost}

Date: {MinDate}

-------------

I'm using the email template to send to a lot of contacts an Email using Apex (due to a lot of logic) and sometimes I even duplicate the email template with different data to the same contact.

In my Apex code, I'm searching the Word I want to replace with my data - after I do my logic.

Every line break [Enter] is replaced within the HTMLBody with <div>&nbsp;</div>

Now, if the contact doesn't have a {cost} to fill in, I want to replace {cost} and {price} with an empty string (''), and it work great so far - but the <div>&nbsp;</div> stays there, So what I get is an unnecessary line break in my Email :

body variable has the HTMLValue of my email template.

 body = body.replace('{price}:','');
  body = body.replace('{cost}','');

-----------------------

Name : {ContactName}

Account : {AccountName}

Unnecessary line break

Date: {MinDate}

-------------

I wonder, how can I delete the <div>&nbsp;</div> of the same row I just delete.

of course, replacing the &nbsp; doesn't give the desire solution - Its delete all line breaks in my template.

 body = body.replace('&nbsp;','');

Many thanks,

0

1 Answer 1

4

You shouldn't replace line breaks (\r\n) with <div>&nbsp;</div>, because that's semantically invalid HTML. Instead, you should split the lines by line break, and wrap them in <p>:

Name : {ContactName}
Account : {AccountName}
{price} : {Cost}
Date: {MinDate}

Should become:

<p>Name : {ContactName}</p>
<p>Account : {AccountName}</p>
<p>{price} : {Cost}</p>
<p>Date: {MinDate}</p>

Of course, by your own reckoning, this still leaves us with <p> : </p>; you could replace that much more reliably:

body.replace('<p> : </p>','');

That said, I'd look into using Visualforce templates and the Messaging.renderStoredEmailTemplate method instead, which gives you the full power of rendering without manual parsing.

1
  • Right! THANK YOU!! that helped me a lot!
    – Salvation
    Jul 15, 2021 at 11:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .