将客户端JavaScript模板放在HTML或JavaScript中? [英] Place client-side JavaScript templates in HTML or JavaScript?

查看:102
本文介绍了将客户端JavaScript模板放在HTML或JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端模板应该如下(使用下划线的模板引擎):

Should client-side templates like the following (using underscore's templating engine):

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

是放在单独的HTML文件还是单独的JavaScript文件中?我知道它可以双向工作。

be placed in an separate HTML file, or a separate JavaScript file? I know it could work both ways.

例如,一个JavaScript文件可能只包含一个字符串变量列表,如下所示:

For example, a JavaScript file could just contain a list of string variables like so:

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

但我也看到以下内容:

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

仅从分离关注的角度来看,模板存储属于哪里?

Just from a Separation of Concerns standpoint, where does the template storage belong?

推荐答案

我通常会使用一个资产管理系统来连接和缩小javascripts和css,并将客户端模板文件转换为挂起全局变量的JS字符串。这种事情取决于您的平台,但在rails世界中,您想要查看 jammit 或< a href =https://github.com/sstephenson/sprockets\"rel =nofollow>链轮(现在是铁轨的一部分)

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)

如果我没有合适的资产管理,我通常会最终使用脚本标记方法,模板在服务器上拆分为部分,并包含在页面底部。使用它有点痛苦,但是IMO不仅仅是你的简单示例字符串模板真的不应该存在于你的javascript文件中。

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.

这篇关于将客户端JavaScript模板放在HTML或JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆