Search code examples
google-apps-scriptweb-applications

& is always being decoded (which I don't want) using HtmlOutput or HtmlTemplate


I've created a script one or two years ago, which exports all strings for Android and iOS. It shows a dialog with textareas for each language with the full strings file in the textarea. It always worked fine until UiApp was removed.

So right now I've tried using HtmlService and HtmlTemplate. Both result in & being converted to &.

HtmlOutput I'm using this code:

    var htmlOutput = HtmlService.createHtmlOutput().setWidth(800).setHeight(600);
    htmlOutput.append('<textarea style="width: 100%; height: 100px;" id="' + id + '">' + content + '</textarea>');

This produces a textarea with for example this:

<string name="terms">Terms & Privacy</string>

For HtmlTemplate I've tried:

    var templateString = '<textarea style="width: 100%; height: 100px;" id="' + ("export_" + i) + '">' + '<?!=' + texts[i] + '?>' + '</textarea>';
//  Or this one without Force-printing scriptlets
//  var templateString = '<textarea style="width: 100%; height: 100px;" id="' + ("export_" + i) + '">' + texts[i] + '</textarea>';
    HtmlService.createTemplate(templateString).evaluate().setWidth(800).setHeight(600);

I tried to use Force-printing scriptlets which gives an even weirder output:

Terms & Privacy

It doesn't even give the <string> tags around it. When I leave the Force-printing scriptlets away it gives the same result as HtmlOutput.


Some extra info

Before I'm exporting it using these methods I'm making sure every string is being converted so it will be the correct output for Android and iOS. For example I'm using this piece of code to convert a string:

var text = o.texts[textIndex];
text = text.replace(/&/g, "&amp;");
'<string name="' + identifier + '">' + text + '</string>' + "\n";

This is of course not all, but just to give an idea how the script works.


Solution

  • Solution

    You can utilize the appendUntrusted() method to return HTML without being parsed. Everything you append to output via this method will not be treated as markup (think of it as setting textContent property).

    Sample

      var htmlOutput = HtmlService.createHtmlOutput().setWidth(800).setHeight(600);
          htmlOutput.append('<textarea style="width: 100%; height: 100px;" id="' + id + '">');
          htmlOutput.appendUntrusted(content);
          htmlOutput.append('</textarea>');
    

    Output

    And this is a sample output (I used '&amp; &amp; and two' as content)

    enter image description here

    Useful links

    1. appendUntrusted() method reference;