Host client-side JavaScript templates in HTML or JavaScript?

If client-side patterns look like this (using an underscore pattern):

<p class="foo"><%= bar %></p> 

fits in a separate HTML file or separate JavaScript file? I know this can work both ways.

For example, a JavaScript file may contain only a list of string variables:

 var cute = '<p class="the"><%= unicorn %></p>'; var fb = '<p class="new-design"><%= sucks %></p>'; 

But I also saw the following:

 <script type="text/template" id="omg-template"> <span id="swag-name"><%= name %></span> </script> 

In terms of Separation of worries, where does the template repository belong?

+6
source share
4 answers

I usually use an asset management system that combines and minimizes javascripts and css and converts client-side template files into JS strings that depend on the global var. It depends on your platform, but in the world of rails you want to see jammit or sprockets (which is now part of the rails)

If I don’t have decent asset management, I usually use the script tag method, with the templates split into partial on the server and included at the bottom of the page. This is a kind of pain you can work with, but IMO is nothing more than your simple sample line patterns really should not be embedded in your javascript file.

+4
source

If you use a logical client-side template engine, such as Transparency , the templates can be embedded in the main HTML, since the templates themselves are valid HTML,

Example:

 <!-- Template --> <div id="template"> <span class="greeting"></span> <span class="name"></span> </div> // Data var hello = { greeting: 'Hello', name: 'world!' }; <!-- Result --> <div id="template"> <span class="greeting">Hello</span> <span class="name">world!</span> </div> 

For templates to be used as widgets, the <div> container is hidden.

Entering HTML code into Javascript code blocks and Javascript strings is ugly and should be avoided if possible. This is not syntax, and you easily skip errors.

+4
source

I prefer the second option for the following reasons:

  • Using strings means handling quotes, etc.
  • Multiline patterns are a pain in Javascript, since you cannot have multiline strings without concatenation. Templates of any length will be more legible on multiple lines.
  • Lack of syntax highlighting in JS strings.

But when using the second option, you need to somehow load the template file or include it in your HTML code or embed it in your HTML at build time. Plus there is more overhead due to the script tag, and you should get the string from the DOM using jQuery .html() or a similar method. So, in terms of performance, a line option might be better - that’s why @Matt's suggestion of placing it in lines at build time is probably best.

+3
source

You can use jQuery templating engine and load all your templates into an external js file.

0
source

Source: https://habr.com/ru/post/897953/


All Articles