Javascript 模板不运行:语法错误:函数体之后的意外垃圾,以“}”开头

Javascript template doesnt run: SyntaxError: unexpected garbage after function body, starting with '}'

本文关键字:开头 意外 之后 运行 语法 Javascript 函数体 错误      更新时间:2023-09-26

我有我的开发服务器(django 1.5)。在这个服务器中,我可以毫无问题地创建 JavaScript 模板。

空视图仅返回一个模板。现在,在这个模板中,我有以下代码:

{% load verbatim %}
<!DOCTYPE html>
<html>
<head>
<link href="http://0.0.0.0:8080/css/bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="http://0.0.0.0:8080/css/bootstrap/2.3.1/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />

</head>
<body>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="span12">
                <div id="result"></div>
            </div>
        </div>
    </div>
    <!-- The javascript template -->
    <script src="http://blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
    {% verbatim %}
    <script type="text/x-tmpl" id="tmpl-demo" src="">
        <h3>{%=o.title%}</h3>
        <p>Released under the
        <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p>
        <h4>Features</h4>
        <ul>
        {% for (var i=0; i<o.features.length; i++) { %}
            <li>{%=o.features[i]%}</li>
        {% } %}
        </ul>
    </script>
    {% endverbatim %}

    <!-- The javascript -->
    <script type="text/javascript">
        var data = {
                "title": "JavaScript Templates",
                "license": {
                    "name": "MIT license",
                    "url": "http://www.opensource.org/licenses/MIT"
                },
                "features": [
                    "lightweight & fast",
                    "powerful",
                    "zero dependencies"
                ]
            };
            document.getElementById("result").innerHTML = tmpl("tmpl-demo", data);
    </script>
    </body>
</html>

记录:使用标签{% verbatim %},因此 django 模板引擎忽略模板脚本,因为它们都使用非常相似的语法

现在,当我尝试在使用 apache 和 django 1.4.5 的主服务器中运行相同的页面时,模板脚本似乎无法识别。在Firebug中,我收到以下错误: SyntaxError: unexpected garbage after function body, starting with '}'

如果我删除 text/x-tmpl 脚本中的所有 javascript 模板标签,则不会显示任何错误。

这让我认为浏览器认为text/x-tmpl是javascript,因为:

  • 我缺少在视图中发送内容
  • 我的 apache 配置中缺少某些内容

我试图四处搜索,但我什么也找不到。

你们中有谁知道如何解决这个问题吗?

谢谢:)

编辑 1:这是指向javascript模板wiki的链接https://github.com/blueimp/JavaScript-Templates

编辑 2:这是 django 视图

@login_required
def test(request):
    return render_to_response('myapp/test.html', locals(), context_instance = RequestContext(request))

首先,谢谢大家的帮助:)

我之前制作了一个自定义的逐字模板标签用于 django 1.4,正如 Alasdair 指出的那样,一个默认的逐字标签被添加到 django 1.5 中......这是我从未注意到的。

话虽如此,在我的开发服务器(运行 django 1.5)中使用了 django 逐字模板标签......而另一台服务器(运行 Django 1.4)正在使用我的自定义模板标签。

关于萤火虫错误。由于令牌之间的间距错误,它被抛出。

Django 1.5 逐字标签将呈现{% } %},我的自定义模板标签将呈现{%}%}

所以我只是在我的自定义模板标签中添加了正确的间距,问题就解决了。

如果您尝试使用 verbatim ,只需使用

{% verbatim %}
    #Your codes which may affect django template syntax
{% endverbatim %}

无需{% load verbatim %}