Hello!

Question on jQuery Templates plugin. Is it possible to place the template itself not in the HTML code, but inside the JavaScript code?

For example. In the classic version looks like this: HTML:

<script id="tpl" type="text/x-jquery-tmpl"> <div class="test"> <h2> Переменная равна: ${title} </h2> </div> </script> <div id="test1"></div> 

Js:

  $(function () { $("#tpl").tmpl({ "title" : "Hello World" }).appendTo('#test1'); }); 

I would not like to have text/x-jquery-tmpl templates in the HTML code of the page. Therefore, I transferred the template part to the JS code:

  $(function () { $("<div class="test"><h2>Переменная равна: ${title}</h2></div>").tmpl({ "title" : "Hello World" }).appendTo('#test1'); }); 

But an error occurs!

Tell me, please, what is wrong and how can I transfer a template from HTML to JavaScript code.

Thank!

  • "But an error occurs!" - colleague, open the veil of secrecy - what is the mistake? - Igor
  • @igor writes "Uncaught SyntaxError: missing) after argument list". Maybe this is because of double quotes? - Pavel
  • @Igor yes, I’m a bit dumb, I just had to escape quotes - Pavel

1 answer 1

 $("<div class="test"><h2>Переменная равна: ${title}</h2></div>").tmpl({ "title" : "Hello World" }).appendTo('#test1'); 

The quotation marks " must be replaced by ' , so that doubles inside the string should not be escaped:

 $('<div class="test"><h2>Переменная равна: ${title}</h2></div>').tmpl({ "title" : "Hello World" }).appendTo('#test1'); 

But in general, the code is suspicious - first we form a dom-tree with templates, and then we give it to the template engine - we did not invent template for this, you are doing something wrong.