通过ajax加载下划线模板会丢失html,需要转义"<";>"

Loading underscore template via ajax loses html, need to escape "<", ">"

本文关键字:quot 转义 html 下划线 加载 ajax 通过      更新时间:2023-09-26

我使用ajax .js (https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js)加载页面内容。默认情况下,该脚本从页面异步加载脚本,如下所示:

$scripts.each(function(){
    var $script = $(this), 
        scriptText = $script.text(),
        scriptType = $script.attr('type'),
        scriptId = $script.attr('id');
    scriptNode = document.createElement('script');
    if(scriptType) {
        $(scriptNode).attr('type', scriptType);
    }
    if(scriptId) {
        $(scriptNode).attr('id', scriptId);
    }
    scriptNode.appendChild(document.createTextNode(scriptText));
    contentNode.appendChild(scriptNode);
});

问题是,对于我的下划线模板,使用$script.text()完全忽略了模板的HTML内容。

另一方面,使用$script.html()转义模板代码中的<>字符(下划线的<%等…),输出最终看起来像:

&lt;% _.each(things,function(thing,key,list){ %&gt;

我如何得到脚本的内部html/文本完整,使其功能正常与AJAX加载?谢谢!

完整的模板脚本如下:

    <script type="text/html" id='furniture-template'>
        <div class="accordion collapse">
            <div class="accordion-group">
                <% _.each(things,function(thing,key,list){ %>
                <div class="accordion-heading">
                    <a class="no-ajaxy accordion-toggle ic-minus block collapsed" data-toggle="collapse" href="#things-<%= thing.slug %>">
                        <%= thing.title %>
                    </a>
                </div> <!-- header -->
                <div id="things-<%= thing.slug %>" class="accordion-body collapse">
                    <div class="accordion-inner">
                        <% for(var item in thing.items) { %>
                        <div class="item">
                            <% if( thing.items[item].images == true ) { %>
                                <a class="no-ajaxy" data-target="<%= thing.items[item].slug %>-gal" class="img-link ic-cam fl" title="View an example"></a>
                            <% } %>
                            <a 
                                class="item-add ic-plus" 
                                data-title="<%= thing.items[item].title %>" 
                                data-slug="<%= thing.items[item].slug %>"
                                data-img="<%= thing.items[item].images %>"
                                data-shorthand="<%= thing.items[item].shorthand %>"
                                data-price="<%= thing.items[item].price %>"
                            >
                                <%= thing.items[item].title %>
                            </a>
                        </div>
                        <% } %>
                    </div> <!-- inner -->
                </div> <!-- accordion-body -->
            <% }); %>
            </div>
        </div>
    </script>

奇怪的情况。简单的解决方案是使用.html()和未转义的转义下划线序列,这可能是你想要的(也就是说,你可能不想对所有内容进行未转义):

$script.html().replace(/&lt;%/gi, '<%').replace(/%&gt;/gi, '%>')

你没试过吗:

contentNode.innerHTML = scriptnode;