Place client-side JavaScript templates in HTML or JavaScript?

你。 提交于 2019-12-05 07:55:11

I usually will use an asset management system that concatenate and minify javascripts and css, and translate client side template files into JS strings hanging off a global var. This sort of thing depends on your platform, but in the rails world you want to look at jammit or sprockets (which is now part of rails)

If I don't have decent asset management, I will usually end up using the script tag method, with the templates split out into partials on the server, and included into the bottom of the page. It is sort of a pain to work with, but IMO anything more then your simple example string templates really shouldn't exist inline in your javascript file.

If you are using logicless client-side template engine like Transparency templates can be embedded in main HTML because 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 in widget like manner a hidden <div> container does fine.

Putting HTML'ish code to Javascript codeblocks and Javascript strings is ugly and should be avoided if possible. It is not syntax highlightable and you miss errors easily.

I greatly prefer the second option, for the following reasons:

  • Using strings means dealing with escaping quotes and the like.
  • Multi-line templates are a pain in Javascript, as you can't have multi-line strings without concatenation. Templates of any length will be more legible on multiple lines.
  • No syntax highlighting in JS strings.

But using the second option requires loading your template file somehow, or including it in your HTML, or sticking it into your HTML at build time. Plus there's more data overhead due to the script tag, AND you have to get the string from the DOM using jQuery's .html() or a similar method. So performance-wise, the string option might be better - which is why @Matt's suggestion of putting it into strings at build time is probably best.

You could use jQuery's templating engine and load all your templates in an external js file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!