function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Steve ThurstonSteve Thurston 

How to copy-and-paste HTML into Apex variable and not get "line breaks not allowed in string literals" error?

I have a customer who has very specific HTML that I need to use to format an email.  This HTML needs to be built in Apex and then passed to Visualforce.  (I need to query data in order to build the HTML content.)

They have provided a sample email with all the HTML that I need to generate.  I would like to copy-and-past this into my Apex variable.  However, because the HTML code is spread over multiple lines, I can't put it into a String because I get the error:

"line breaks not allowed in string literals"

This HTML is quite long, and removing the line breaks will not only make it almost impossible to analyse and troubleshoot, but I would have to go through each line of the HTML and remove its line breaks.

How can I add HTML to an Apex variable that displays across many lines in the Apex code, which can then be used to build an email?
jigarshahjigarshah
Steve,

You would definitely need to use a String variable in Apex to hold the generated html. The approach I would recommend would be as follows.
1. Query the data from the Sobject required to generate your html string.
2. Write a separate html generator utility class in Apex to generate the html string. If you have the flexibility of generating the html from Javascript within your Visualforce page, you can leverage that as well. You could use this online utility (http://pojo.sodhanalibrary.com/string.html) to generate html as Strings for Javscript.

One thing you may need to check for is if you are prefixing the special characters such as single quotes - ', double quotes ", etc. stored within your Apex String variable holding the html string with a backslash i.e. \. This is requried to escape the specific special character and tells the Apex compiler to treat them as String literals.

If you can share your code, will possibly be able to help you with the exact issue.

Please DO NOT forget to mark this thread as SOLVED if it helps resolve your issue.