O que é x-tmpl?
O x-tmpl impede o navegador de interpretar o script JavaScript. Para usar JQuery x-tmpl, precisamos do arquivo jquery-tmpl JavaScript. O método jQuery.tmpl() encadeia os métodos .appendTo, .prependTo, .insertAfter ou .insertBefore.
Sintaxe:
tmpl([data], [options])
Por exemplo:
$("#myTemplate").tmpl(Data).appendTo("ul");
$.tmpl(template, [data], [options])(string containing markup, HTML Element, or Name of named template)
Por exemplo:
$.tmpl("namedTemplate", Data).appendTo("ul");
Exemplo:
$.tmpl( "<li>${Name}</li>", { "Name" : "GFG" }).appendTo( "#target" );
JQuery x-tmpl é usado para composição de template.
Uso de x-tmpl ( lado do cliente ) :
- Instale o pacote blueimp-tmpl com npm:
npm install blueimp-tmpl
- Incluir script de modelos JavaScript na marcação HTML:
<script src="js/tmpl.min.js"></script> // Implementing them into the variables. var template = '<p>Hello!</p>' ;
- Adicione uma seção de script com o tipo “text / x-tmpl”:
<script type="text/x-tmpl" id="tmpl-demo"> <h3>GFG}</h3> <h4>Features</h4> <ul> {% for (var i=0; i<o.features.length; i++) { %} <li>{%=o.features[i]%}</li> {% } %} </ul> </script>
- Crie um objeto JavaScript para usar dados para o modelo:
var data = { title: 'GFG', geeky: { name: 'GFG', }, features: ['more content', 'powerful', 'zero dependencies'] }
- Chame o método tmpl():
document.getElementById('result').innerHTML = tmpl('tmpl-demo', data)
Uso de x-tmpl ( lado do servidor ) :
- Instale o pacote blueimp-tmpl com NPM:
npm install blueimp-tmpl
- Adicione um arquivo template.html:
<!DOCTYPE HTML> <title>GFG</title> <h4>Features</h4> <ul> {% for (var i=0; i<o.features.length; i++) { %} <li>{%=o.features[i]%}</li> {% } %} </ul>
- Adicione um arquivo 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/')
- Execute o aplicativo:
node server.js
Exemplo: Um exemplo simples de x-tmpl.
<script type='text/x-jquery-tmpl' id='person-template'> <div class='person'> <strong>Name: </strong> ${ Name } <br/> <strong>Age: </strong> ${ Age } <br/> <strong>Country: </strong> ${ Country } <br/> </div> </script>
Agora, vamos implementar o código acima com a saída necessária:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script src=
"http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js">
</script>
<body>
<h3>Employee Details</h3>
<div class="emp-detais"></div>
</body>
<script type="text/x-jquery-tmpl"
id="emp-template">
<div class='person'>
<strong>Name:</strong> ${ Name } <br />
<strong>Skills: </strong><br />
{{each Skills}}
${Skill} <br />
{{/each}}
</div>
</script>
</body>
</html>
Exemplo 2:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR
/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Template Caching</title>
<link href="6_Site.css"
rel="stylesheet"
type="text/css" />
</head>
<body>
<h1>Products</h1>
<div id="productContainer"></div>
<button id="more">More</button>
<script type="text/javascript" src=
"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js">
</script>
<script type="text/javascript" src=
"http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js">
</script>
<script type="text/javascript">
// Globals
var pageIndex = 0;
// Create an array of products
var products = [];
for (var i = 0; i < 100; i++) {
products.push({ name: "Product " + (i + 1) });
}
// Get the remote template
$.get("ProductTemplate.htm", null, function (productTemplate) {
// Compile and cache the template
$.template("productTemplate", productTemplate);
// Render the products
renderProducts(0);
});
$("#more").click(function () {
pageIndex++;
renderProducts();
});
function renderProducts() {
// Get page of products
var pageOfProducts =
products.slice(pageIndex * 5, pageIndex * 5 + 5);
// Used cached productTemplate to render products
$.tmpl("productTemplate", pageOfProducts)
.appendTo("#productContainer");
}
function formatPrice(price) {
return "$" + price.toFixed(2);
}
</script>
</body>
</html>
Saída:
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva