doufeng3602 2013-12-16 12:19
浏览 321
已采纳

为什么html / template不显示所有html条件注释?

I have a simple Go HTML template which contains HTML conditional comments:

package main

import (
    "html/template"
    "os"
)

var body = `<!doctype html>
<html>
  <head>
    <!--[if !IE]><!--><script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><!--<![endif]-->
    <!--[if gte IE 9]><script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><![endif]-->
    <!--[if lt IE 9]><script src="http://code.jquery.com/jquery-1.10.2.min.js"></script><![endif]-->

  </head>
</html>`

func main() {
    tmp := template.Must(template.New("tmp").Parse(body))
    tmp.Execute(os.Stdout, nil)

}

This produces:

<!doctype html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>



  </head>
</html>

Why does html/template remove those conditional comments after compiling?

  • 写回答

5条回答 默认 最新

  • doutao1171 2013-12-17 10:24
    关注

    Since your question was Why, I will try to explain why comments are stripped away.

    First of all, the purpose of the html/template package is to be safe. The documentation states:

    Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.

    This is done through context-sensitive escaping. In a Golang-nuts thread Kyle Lemons provide an example where conditional comments would currently break this safety unless the comments were stripped away:

    <p>
    <!--[if lt IE 9]><script><![endif]-->
    {{.Stuff}}
    <!--[if lt IE 9]></script><![endif]-->
    </p>
    

    In this case, any value in {{.Stuff}} will be executed as Javascript on some browsers and should therefore be escaped to be safe . This would require the template engine to be aware of this browser-specific interpretation of the comment, and any other non-standard behavior in all the browsers out there. This is not feasible.

    Instead, html/template was designed to strip away any comments to ensure that the HTML it produces is safe from any injection attack.

    Workaround

    As mentioned by Dave, it is possible to use template.HTML to insert such comments. However, because of the security risk, the documentation for template.HTML states (my emphasis):

    HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!