中,其中包含看起来像 PHP 之外的代码,但带有 JavaScript 标记。谁可以给我解释一下这个?这是合法的吗?" /> 中,其中包含看起来像 PHP 之外的代码,但带有 JavaScript 标记。谁可以给我解释一下这个?这是合法的吗?"> 中,其中包含看起来像 PHP 之外的代码,但带有 JavaScript 标记。谁可以给我解释一下这个?这是合法的吗?" />
ChatGPT解决这个技术问题 Extra ChatGPT

Explanation of <script type = "text/template"> ... </script>

I just stumbled upon something I've never seen before. In the source of Backbone.js's example TODO application (Backbone TODO Example) they had their templates inside a <script type = "text/template"></script>, which contained code that looks like something out of PHP but with JavaScript tags.

Can someone explain this to me? Is this legit?

Great question and answer. I just ran across this trick in the new YUI App Framework code: new.yuilibrary.com/yui/docs/app/app-todo.html
What about type="text/tcl" which I saw in the W3C doc? How to use it? (Should I ask another question?)
@L01man yes, you should ask another question.

r
rolling stone

Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.

By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.

Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.


@Matt, exactly that. At the same time it's easy to retrieve the full text again using .innerHTML, hence it's common practice now among templating engines.
Well isn't that just fantastic news! I've been looking for a solution like this.. Thanks for your response and follow-up!
hi, different Matt here. Would