使用句柄解释html字符串,但转义脚本标记 [英] Interpret html string using handlebars but escape script tags

查看:111
本文介绍了使用句柄解释html字符串,但转义脚本标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的页面引入了一串html,除了脚本标记外,我认为它是html安全的。我知道,三个大括号将转义HTML,什么是步骤忽略任何脚本标记?



示例

  var foo =< h1> Foo< / h1><脚本>某些可能在此处的脚本< / script>< p>栏< / p> ; 

然后在我的.hbs中:

  {{{foo}}} 

我想请参阅h1和段落,但留下脚本。



预先致谢。

解决方案

您有几个选项:


  1. 在将脚本标记作为上下文传递到Handlebars之前,除去脚本标记

  2. 创建一个Handlebars helper来代替三重花括号表达式,如下所示:

  3. $ b $


      Handlebars.registerHelper('strip-scripts',function(context){
    var html = context;
    //上下文变量是您将传递给帮助程序的HTML
    //从HTML中剥离脚本标记,并将其作为Handlebars.SafeString返回
    return new Handlebars.SafeString(html );
    });

    然后在您的模板中使用它:

      {{strip-scripts foo}} 

    您在使用助手时不需要使用三重花括号,因为你的助手已经返回一个SafeString。



    助手可能比第一个选项更有用,因为你可以在整个模板中重复使用它。



    查看此StackOverflow问题以获取有关如何安全删除脚本标记的帮助:



    如果你用Node.js做这个服务器端,你可以使用Cheerio而不是jQuery。


    I'm bringing in a string of html for my page and I consider it html-safe except for script tags. I'm aware that triple braces will escape the html, what are the steps to leave out any script tags?

    Example

    var foo = "<h1>Foo</h1><script>some script that might possibly be in here</script><p>bar</p>
    

    then in my .hbs:

    {{{foo}}}
    

    I would like to see the h1 and the paragraph but have scripts left out.

    Thanks in advance.

    解决方案

    You have a couple of options:

    1. Remove the script tags before passing it as context into your Handlebars template.

    2. Create a Handlebars helper to use in place of the triple curly braced expression. Something like this:

        Handlebars.registerHelper('strip-scripts', function(context) {
          var html = context;
          // context variable is the HTML you will pass into the helper
          // Strip the script tags from the html, and return it as a Handlebars.SafeString
          return new Handlebars.SafeString(html);
        });
    

    Then use it in your template like this:

        {{strip-scripts foo}}
    

    You don't need to use triple curly braces when using the helper, because your helper returns a SafeString already.

    The helper may be more beneficial than the first option, because you can reuse it throughout your templates.

    Check out this StackOverflow question for help on how to strip the script tags out safely: Removing all script tags from html with JS Regular Expression

    If you're doing this server-side with Node.js, you can use something like Cheerio instead of jQuery.

    这篇关于使用句柄解释html字符串,但转义脚本标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆