Search code examples
htmlgoogle-apps-scriptgoogle-sites

why some html tags do not seem to work with HtmlService in google apps script?


I created a simple random quote generator for my google site. The quotes are stored in a spreadsheet and included in a page of my website via google apps script. Specifically, I have a script using HtmlService "in bundle" with an html page.

Overall, the code seems to work ok. However I seem to be unable to use some basic html tags, such as < p > or < b >.

I have two possible issues:

1) I'm passing plain text (text1), and enclosing it within < b >< /b > tags in the html document. However the text is not bold.

2) I'm passing some text containing html tags (text_tag). These are not interpreted as such in the html file.

I'm attaching a mwe below. I have stripped it of all the part concerning the retrieval of the text from a spreadsheet.

The google apps script I'm using is

function doGet(e) {
    var pageDetailsHTML = HtmlService.createTemplateFromFile('formattedText');
    var page = SitesApp.getActivePage()

    var text1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
    var text_tag = "<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>" + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ";

    var pageDetailsObj = {
     text1   : text1,
     text_tag: text_tag,
    }
    pageDetailsHTML.e = e;
    pageDetailsHTML.pageDetailsObj = pageDetailsObj;
    return pageDetailsHTML.evaluate()
     .setTitle('Dettagli della pagina');
   Logger.log('e = ' + JSON.stringify(e));
   }

The html code referred to by the script (formattedText.html) is

<!DOCTYPE html>
<html>
 <head>
 <base target="_top">
 <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
 <body style="background-color:#e6f2fe">
  <p><?= pageDetailsObj.text1 ?></p>
  <p><b><?= pageDetailsObj.text1 ?></b></p>
  <p><?= pageDetailsObj.text_tag ?></p>    
 </body>
</html>

Neither the < b > tag in the second line nor the html tags in "text_tag" seem to work.

What am I doing wrong?

Thanks a lot for your help.

Francesco


Solution

  • The scriplets which you have used is printing scriptlet (<?= ... ?>) it will just print the value as it is as it does contextual escaping.

    In order to display the value along with HTML tags you need to use "Force-printing scriptlets" (<?!= ... ?>);

    <p><?!=pageDetailsObj.text_tag ?></p>