简体   繁体   中英

Does Javascript Have Open and Close Tags Equivalent to PHP?

I came across this sort of code on a WordPress admin page:

<script type="text/html" id="tmpl-uploader-inline">
    <# if ( data.message ) { #>
        <h3 class="upload-message">{{ data.message }}</h3>
    <# } #>
</script>

Are the tags <# and #> part of javascipt/html syntax or is something else going on here? I tried googling, but google seems to have issues when searching for certain types of symbols. They never make it to the search results.

UPDATE: Based on the answers so far, if the code in the tags is processed by a template engine on the server side, then why is the exact code showing up as page source in the browser? Shouldn't it show just the results of template processing?

General technology

This is a Javascript template . Wordpress uses Backbone.js since version 3.4.1 . You can model a View in Backbone.js, which is automatically updated, when the underlying Javascript object changes, see the corresponding Backbone.js documentation .

Backbone.js again is based on underscore.js , which is basically a collection of Javascript utility functions. One of the functions is _.template , which takes a template string (for example the content of the HTML tag you posted) and a Javascript data object, and replaces variables with values from the data object and evaluates simple expressions.

Example from the underscore.js manual:

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

Wordpress adaptions

The normal _.template syntax would be <%= name %> , but for whatever reason the Wordpress developers decided that the so called ERB-style is not appropriate and changed it. You can see that in wp-includes/js/wp-util.js , in version 3.9. around line 20, where the options hash is overriden with some regular expressions. Basically the syntax is changed to use {{ name }} to output the value of a variable and <# if ... #> is being evaluated. (The first one looks a bit like the syntax mustache.js uses.)

Further reading

Here is a tutorial ( part 1 , part 2 ) which covers the usage of Backbone.js in Wordpress backends.

And here someone gathered a lot of resources around that topic in Wordpress (and in general).

这些标签不是JavaScript或HTML的一部分,而是由模板引擎使用的标签。

It does have Open and Close tags. Those are

<script></script>

The other tags

<# #>

are template tags. The difference between them is that the <script> tags will run on the client's browser, and the other ones ( <# ) are run on the server before sending the page to the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM