下划线模板在HTML中产生神秘的404错误

Underscore template in HTML generating mysterious 404 errors

本文关键字:错误 HTML 下划线      更新时间:2023-09-26

好的,我有这个下划线模板(简化版),从_template.html.erb渲染,在我的Rails应用程序,在页面的某个地方:

<script type="text/html" id="mytemplate">
<div class="foo">
  <img src="{{= my_variable }}" />
</div>
</script>

然后我像这样渲染它,在其他地方,当需要的时候:

// change it to mustache-style because of defaults clashing with erb
_.templateSettings = {
  interpolate: /'{'{'=(.+?)'}'}/g,
  evaluate: /'{'{(.+?)'}'}/g
};
options = {
  my_variable: '/foo/bar/baz.img'
}
compiled = _.template($("#mytemplate").html());
$(compiled(options)).appendTo("#wherever");

这,理论上应该工作得很好,它确实,除了像这样的错误开始弹出在服务器日志和其他地方,浏览器404的url,如:http://example.com/{{=%20my_variable%20}},或http://example.com/foo/{{=%20my_variable%20}}

现在,我的预感是它与事实有关,它是一个img标签,不知何故浏览器试图从页面GET它,即使它被包装在script标签,但我不知道为什么在地球上。这是许多人推荐的在HTML中嵌入下划线模板的方法之一。我也不能把它归因于旧浏览器和/或机器人,因为服务器日志显示这些是真实的人使用最新的Chrome等。

编辑:经过更多的调查,1。它只发生在少数人(唯一的ip)身上。他们都在使用最新版本的Chrome浏览器。所以可能是分机出了问题?

任何想法?

您必须将type="text/html"更改为不存在的type="x-template"(或任何真正的东西)

如果缓存已清空,则此操作正常工作。

如果没有

,那么您可以使用外部模板(您加载的文件)。但是如果你想保持它们内联,那么转义有问题的字符(使用内部JS字符编码)。这将被JS解析,但不会被HTML解析器捕获。

您可以使用此工具:http://mothereff.in/js-escapes(取消选中"仅转义非ASCII和不可打印的ASCII字符"框)

它可能是这样的:

<script type="text/html" id="mytemplate">
<div class="foo">
  'x3Cimg src="{{= my_variable }}" />
</div>
</script>