问题描述
如果我有一个HTML文件test.html:
If I have an HTML file test.html:
<p><?= str ?></p>
还有一个脚本功能:
var t = HtmlService.createTemplateFromFile("test.html");
t.str = "test\nstring";
var content = t.evaluate().setSandboxMode(...).getContent();
Logger.log(content);
有没有办法用HTML换行符安全地替换换行符?我可以使用String.prototype.replace()将 \ n
替换为< br/>
,但是然后我必须使用< ;?!=
禁用HTML模板引擎的上下文转义.我正在处理不受信任的输入,因此需要转义和换行符的智能处理.在上下文中拥有它会很好.就目前情况而言,我编写了自己的转义符,但这仅适用于一种情况.
Is there any way to safely replace the newline with an HTML line break? I can use String.prototype.replace() to replace \n
with <br/>
, but then I'd have to use <?!=
to disable the HTML templating engine's contextual escaping. I'm dealing with untrusted input and so I need both escaping and smart handling of line breaks. Having it contextually would be nice. As things stand, I wrote my own escaper, but it is only good for one context.
推荐答案
我为您的方案看到了两个选项,简单的一个就是完全忘记替换,并使用< pre>标签,它将显示您的换行符(和其他格式的字符)
I see two options for your scenario, the simple one is to forget the substitution entirely and use a <pre> tag, which will render your line breaks (and other formatting chars)
< pre><?= str?></pre>
第二步是执行替换并使用自定义功能对输入内容进行清理,以便您可以安全地使用强制打印脚本.
The second is to perform the substitution and sanitize your input with a custom function, so that you can safely use the force print scriptlet.
在您的html中:
<?!= sanitize(str);?>
以及您的.gs文件中:
and in your .gs:
函数sanitize(val){var vals = val.split('\ n');//在换行符上将字符串分割成一个数组for(var i in vals){vals [i] = Encoder.htmlEncode(vals [i]);//清理数组中的每个元素}返回vals.join('< br/>');//使用< br/>将元素作为字符串连接.作为胶水.}
请注意,在我的示例中,我正在使用此处的库来清理字符串: http://www.strictly-software.com/scripts/downloads/encoder.js
Note, in my example I'm using the library located here to sanitize the strings: http://www.strictly-software.com/scripts/downloads/encoder.js
这篇关于Google Apps脚本:模板化HTML scriptlet中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!