📜  x-tmpl 是什么?

📅  最后修改于: 2022-05-13 01:56:03.171000             🧑  作者: Mango

x-tmpl 是什么?

x-tmpl阻止浏览器解释脚本 JavaScript。要使用 JQuery x-tmpl,我们需要 jquery-tmpl JavaScript 文件。 jQuery.tmpl() 方法链接 .appendTo、.prependTo、.insertAfter 或 .insertBefore 方法。

句法:

tmpl([data], [options])

例如:

$("#myTemplate").tmpl(Data).appendTo("ul");
$.tmpl(template, [data], [options])(string containing markup, 
HTML Element, or Name of named template)

例如:

$.tmpl("namedTemplate", Data).appendTo("ul");

例子:



$.tmpl( "
  • ${Name}
  • ", { "Name" : "GFG" }).appendTo( "#target" );

    JQuery x-tmpl 用于模板组合。

    x-tmpl 的用法客户端

    • 使用 npm 安装 blueimp-tmpl 包:
    npm install blueimp-tmpl
    • 在 HTML 标记中包含 JavaScript 模板脚本:
    
    // Implementing them into the variables. 
    var template = '

    Hello!

    ' ;
    • 添加一个类型为“text/x-tmpl”的脚本部分:
    
    
    • 创建一个 JavaScript 对象以使用模板的数据:
    var data = {
     title:  'GFG',
     geeky: {
       name: 'GFG',
       
     },
     features: ['more content', 'powerful', 'zero dependencies']
    }
    
    • 调用 tmpl() 方法:
    document.getElementById('result').innerHTML = tmpl('tmpl-demo', data)

    x-tmpl 的用法服务器端

    • 使用 NPM 安装 blueimp-tmpl 包:
    npm install blueimp-tmpl
    • 添加文件template.html:
    
    GFG
    

    Features

      {% for (var i=0; i{%=o.features[i]%} {% } %}
    • 添加文件 server.js :
    require('http')
     .createServer(function (req, res) {
       var fs = require('fs'),
        tmpl = require('./tmpl'),
       data = {
           title: 'JavaScript Templates',
           url: 'https://github.com/blueimp/JavaScript-Templates',
           features: ['more content', 'powerful', 'zero dependencies']
         }
       
       tmpl.load = function (id) {
         var filename = id + '.html'
         console.log('Loading ' + filename)
         return fs.readFileSync(filename, 'utf8')
       }
       res.writeHead(200, { 'Content-Type': 'text/x-tmpl' })
      
       res.end(tmpl('template', data))
     })
     .listen(8080, 'localhost')
    console.log('Server running at http://localhost:8080/')
    
    • 运行应用程序:
    node server.js

    示例: x-tmpl 的简单示例。

    
    

    现在,让我们用所需的输出来实现上面的代码:

    HTML
    
    
        
            Page Title
        
        
            
      
            
                

    Employee Details

                
                             


    HTML
    
    
        
            Template Caching
            
        
        
            

    Products

               
                                                     


    示例 2:

    HTML

    
    
        
            Template Caching
            
        
        
            

    Products

               
                                                     

    输出: