代码之家  ›  专栏  ›  技术社区  ›  Jim

在浏览器中调用dust.loadSource()时,编译的模板引用未定义

  •  1
  • Jim  · 技术社区  · 13 年前

    我试图在浏览器中使用dust.js编译的模板(而不是使用node.js的服务器端)来渲染HTML。如果我在客户端javascript中编译模板,它会很好地工作。如果我预编译模板并按照建议将其作为脚本标记包含,则dust.loadSource语句会导致Chrome调试器显示:“Uncaught ReferenceError:nowork is not defined”,其中“nowork”是模板名称。所以

    此HTML和脚本可以工作:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>This Works</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="dust-full-0.3.0.min.js"></script>
    </head>
    <body>
        <div id="bingo"></div>
        <script type="text/javascript">
            var templateKey = 'works';
            var myView = {"people":[{"name":"Fred"},{"name":"Harry"},{"name":"Linda"},{"name":"Mary"}]};
    
            dust.loadSource(dust.compile("{#people}<br/>{name}{/people}", templateKey));
            dust.render(templateKey, myView, function(err, out) {
                $('#bingo').html(out);
            });
        </script>
    </body>
    </html>
    

    但事实并非如此:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>This Doesn't Work</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="dust-full-0.3.0.min.js"></script>
        <script type='text/javascript' src="nowork.js"></script>
    </head>
    <body>
        <div id="bingo"></div>
        <script type="text/javascript">
            var templateKey = 'nowork';
            var myView = {"people":[{"name":"Fred"},{"name":"Harry"},{"name":"Linda"},{"name":"Mary"}]};
    
            dust.loadSource(templateKey);
            dust.render(templateKey, myView, function(err, out) {
                $('#bingo').html(out);
            });
        </script>
    </body>
    </html>
    

    其中包含的nowork.js文件包含:

    (function() {
        dust.register("nowork", body_0);
    
        function body_0(chk, ctx) {
            return chk.section(ctx.get("people"), ctx, {
                "block": body_1
            }, null);
        }
        function body_1(chk, ctx) {
            return chk.write("<br/>").reference(ctx.get("name"), ctx, "h");
        }
        return body_0;
    })();
    

    有人能帮忙吗?

    我刚刚意识到,这可能是因为这些文件没有在安装了node.js的机器上提供。我实际上是在我的台式机上本地工作。就是这样吗?

    1 回复  |  直到 13 年前
        1
  •  1
  •   smfoote    13 年前

    你其实不需要打电话 dust.loadSource 当您提供预编译的模板时。在内部, dust.loadSource(灰尘加载源) 只是做了一个 eval 返回的JavaScript字符串 dust.compile 。如果您移除 dust.loadSource(灰尘加载源) 行,您的模板应该正确渲染。

    Node.js对于您在这里尝试的内容来说是不必要的。事实上,满灰尘也不是必须的。如果您所做的只是在客户端上渲染,则可以使用dust core。