underscore.js模板变量名称正在逃脱,导致其未被渲染

发布于 2025-02-03 09:24:07 字数 858 浏览 2 评论 0原文

我正在使用with inscore.js(backbone.js app)使用渲染模板。我遇到了以下问题,当我尝试获取模板字符串(使用.html(),.text())时,我试图渲染的变量名的一部分被逃脱了:

html file:html file:

        <script type="text/template" id="tpl-note-item">
            <h1> 
                <%= noteTitle %>
            </h1>
        </script>

        var htmlString = $("#tpl-note-item").html();


        //   <h1> 
        //        &lt;%= noteTitle %>
        //    </h1>
        //
        console.log(htmlString); 

        var template = _.template(htmlString);

        html += template({ 
            noteTitle: note.get("title")
        });
        . . .

​代码>&lt;%= notetitle%&gt; 而不是从呼叫到note.get(“ title”)中实际替换变量值。

这似乎是模板的相当基本的用例,所以我肯定我缺少一些东西。任何帮助都将不胜感激。谢谢!

I am playing around with rendering templates using with Underscore.js (Backbone.js app). I'm running into the following issue, where a part of the variable name in the template I am trying to render gets escaped when I try and obtain the template string (using .html(), .text()):

HTML file:

        <script type="text/template" id="tpl-note-item">
            <h1> 
                <%= noteTitle %>
            </h1>
        </script>

.js:

        var htmlString = $("#tpl-note-item").html();


        //   <h1> 
        //        <%= noteTitle %>
        //    </h1>
        //
        console.log(htmlString); 

        var template = _.template(htmlString);

        html += template({ 
            noteTitle: note.get("title")
        });
        . . .

As a result of <%= noteTitle %> being escaped to <%= noteTitle %>, the template gets rendered as:

<%= noteTitle %>
instead of actually substituting in the variable value from the call to note.get("title").

This seems like a fairly basic use case of templates, so I am fairly sure I'm missing something. Any help would be much appreciated. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情深已缘浅 2025-02-10 09:24:07

发布此内容仅几分钟后(一天努力解决),我发现了问题:
上下文中的HTML页面是由我的Golang应用程序渲染的:

template.must(template.parsefiles(&lt; page.html&gt;)))

但是,我使用的是软件包html/template,自动escap会渲染的任何HTML文件。切换到文本/模板做到了这一点。
作为参考,相关的Golang帖子: template> template不必要地逃避到`&lt; ; lt;`但是不是`&gt;`

Just minutes after posting this (and a day grappling with this), I found the issue:
The HTML page in context is being rendered by my Golang app using:

template.Must(template.ParseFiles(<page.html>))

However, I was using the package html/template, which auto-escapes any html file being rendered. Switching to text/template did the trick.
For reference, a related Golang post: Template unnecessarily escaping `<` to `<` but not `>`

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文