Skip to main content
 首页 » 编程设计

jquery之Mustache.js之无法使用 jQuery get() 方法获取外部模板

2026年09月08日2小虾米

我想使用 jQuery 的 get() 方法在我的主页中包含一个外部模板,但我有一个问题。

Web 浏览器的控制台中显示以下消息:

TypeError: Invalid template! Template should be a "string" but "undefined" was given as the first argument for mustache#render(template, view, partials) - (mustache.min.js:1:9011)

index.html

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title></title> 
</head> 
<body onload="myTemplate()"> 
    <div id="target">Loading ... </div> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.min.js"></script> 
    <script type="text/javascript" src="my-script.js"></script> 
</body> 
</html> 

templates.html

<script id="tpl-1" type="text/html"> 
    <p>{{ name }} wins {{ calc }} points</p> 
</script> 

my-script.js

// my-script.js 
 
function myTemplate() { 
 
    $.get("tpl/templates.html", function(templates) { 
        var template = $(templates).filter("#tpl-1").html(); 
 
        var data = { 
            name: "Guy", 
            calc: function () { 
            return 8 + 2; 
            } 
        }; 
 
        var rendered = Mustache.render(template, data); 
        $('#target').html(rendered); 
    }); 
} 

尽管如此,它与 load() 方法配合得很好:

// my-script.js 
 
function myTemplate() { 
 
    $("#target").load("tpl/templates.html #tpl-1", function() { 
        var template = $("#tpl-1").html(); 
 
        var data = { 
            name: "Guy", 
            calc: function() { 
                return 8 + 2; 
            } 
        }; 
 
        var rendered = Mustache.render(template, data); 
        $('#target').html(rendered); 
    }); 
} 

您有运行 get() 方法的想法吗?

请您参考如下方法:

    $(document).ready(function(){ 
 
    function myTemplate() { 
 
    $.get("templates.html", function(templates) { 
        var template = $(templates).filter("#tpl-1").html(); 
 
        var data = { 
            name: "Guy", 
            calc: function () { 
            return 8 + 2; 
            } 
        }; 
 
        var rendered = Mustache.render(template, data); 
        $('#target').html(rendered); 
    }); 
} 
 
$('#target').on('load', myTemplate()); 
 
});