Javascript 中的 HTML 模板?没有在页面中编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3585573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:37:39  来源:igfitidea点击:

HTML Templates in Javascript? Without coding in the page?

javascripttemplates

提问by Dave Jacoby

I am a web guy doing mostly Perl server-side stuff, and I'm slowly coming to a few conclusions.

我是一个 Web 人员,主要从事 Perl 服务器端的工作,我正在慢慢得出一些结论。

  • It is far better to do most of your code via Javascript and toss data back and forth via AJAX than it is to hit submit and reload a mostly-identical page
  • I like jQuery because I like CSS, and it's fun to chain together big long and scary-to-others definitions
  • There's something to that templating stuff.
  • 通过 Javascript 完成大部分代码并通过 AJAX 来回传递数据比点击提交并重新加载几乎相同的页面要好得多
  • 我喜欢 jQuery 因为我喜欢 CSS,并且将长而可怕的定义链接在一起很有趣
  • 那个模板的东西有一些东西。

You want your HTML elements to look like your HTML elements, and it's easier to define that in HTML:

你希望你的 HTML 元素看起来像你的 HTML 元素,在 HTML 中定义它更容易:

<div class="sidebar_elem">
     <a href=""> TEXT</a>
</div>

Than it is to cobble up the same in Javascript or jQuery:

比在 Javascript 或 jQuery 中拼凑出相同的内容:

( '<div/>' )
     .attr('id' , 'sidebar_elem' + i )
     .addclass( 'sidebar_elem' )
     ;
( '<a/>' )
     .attr('href' , link_url )
     .appendTo( '#sidebar_elem' + i )
     ;

This is to say that I am no longer a templating agnostic, but I don't know which templating tool to believe in. I have looked into some jQuery-based templating plugins, but I have yet to become happy with any of them, in part because the ones I've seen seem to want to put all that code into the page itself, which breaks the "Only markup goes into HTML files, only style goes into CSS files, only code goes into JS files" mantra I keep reciting.

这就是说我不再是模板不可知论者,但我不知道该相信哪种模板工具。我研究了一些基于 jQuery 的模板插件,但我还没有对它们中的任何一个感到满意,在部分是因为我看到的那些似乎想将所有代码放入页面本身,这打破了“只有标记进入 HTML 文件,只有样式进入 CSS 文件,只有代码进入 JS 文件”的口号,我一直在背诵.

So, I'm looking for a Javascript-based templating tool that would allow me to have my templates in an outside file so I can have one template change cover a series of web pages. If it's jQuery-based, that's great, less stuff I have to learn, but it isn't a deal-breaker.

所以,我正在寻找一种基于 Javascript 的模板工具,它允许我将模板放在外部文件中,这样我就可以通过一个模板更改来覆盖一系列网页。如果它是基于 jQuery 的,那很好,我需要学习的东西更少,但它不是一个交易破坏者。

采纳答案by cofiem

How about EJS?

EJS怎么样?

Example from their page:

来自他们页面的示例:

"EJS combines data and a template to produce HTML."

“EJS 结合数据和模板来生成 HTML。”

Data:

数据:

{title: 'Cleaning Supplies',  supplies: ['mop', 'broom', 'duster'] }

Template:

模板:

<ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>

Result:

结果:

  • mop
  • broom
  • duster
  • 拖把
  • 扫帚
  • 掸子

回答by Sean Vieira

There are several good ones out there:

有几个不错的:

Mustache.js
Pure.js
Json Template

Mustache.js
Pure.js
Json 模板

If you want a jQuery version, Tempestlooks good.

如果你想要一个 jQuery 版本,Tempest看起来不错。

回答by Mic

The 2 libs I know that do not mix template coding with HTML markups are chain.jsand PURE

我知道不将模板编码与 HTML 标记混合使用的 2 个库是chain.jsPURE

chainmakes only DOM manipulations.
PUREuses a mix of DOM and innerHTMLas the DOM alone can be slow to render bigger templates.

chain只进行 DOM 操作。
PURE使用 DOM 的混合,innerHTML因为单独的 DOM 渲染更大的模板可能很慢。

I'm the main contributor of PURE, and we created it to build a web app on the ajax model you describe.

我是 PURE 的主要贡献者,我们创建它是为了在您描述的 ajax 模型上构建 Web 应用程序。

回答by skrat

Take a look at this one http://ejohn.org/blog/javascript-micro-templating/. Made by John Resig, creator of jQuery, this one doesn't even need jQuery, and it's freaking small. It also stores templates in script tag (Daniel's answer). Example template:

看看这个http://ejohn.org/blog/javascript-micro-templating/。由 jQuery 的创建者 John Resig 制作,这个甚至不需要 jQuery,而且它非常小。它还在脚本标签中存储模板(丹尼尔的回答)。示例模板:

<script type="text/html" id="user_tmpl">
    <% for ( var i = 0; i < users.length; i++ ) { %>
        <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
    <% } %>
</script>

Maybe you can load them using src attribute if you really need them to be in separate files, which I don't think is a wise idea, because it means additional roundtrip to the server. So at the end, for the sake of optimization, you can store them in separate files, but embed them server side in the page that needs them.

如果您确实需要将它们放在单独的文件中,也许您可​​以使用 src 属性加载它们,我认为这不是一个明智的主意,因为这意味着到服务器的额外往返。所以最后,为了优化,你可以将它们存储在单独的文件中,但将它们嵌入到需要它们的页面中。

回答by melihcelik

Since there is no well defined API and a best library for templating, I would suggest you choose one that is actively developed. Below, I briefly explained two libraries that are actively being developed.

由于没有明确定义的 API 和最好的模板库,我建议您选择一个积极开发的库。下面,我简要介绍了两个正在积极开发的库。

jQuery team decided that jQuery Templates will no longer be actively developed or maintained, thus I would strongly suggest NOT using it. See this blog entry.

jQuery 团队决定不再积极开发或维护 jQuery 模板,因此我强烈建议不要使用它。请参阅此博客条目

You can use JsRenderin accordance with JsViewsto take full functionality provided by jQuery Templates and even more like data linking. You can find demos for JsRenderand JsViews. I would suggest using these libraries since they are actively being developed by jQuery UI team but be aware that they are still not even beta!

您可以使用JsRender按照JsViews采取的jQuery模板,甚至更像数据链接提供的全部功能。您可以找到JsRenderJsViews 的演示。我建议使用这些库,因为它们正在由 jQuery UI 团队积极开发,但请注意,它们甚至还不是测试版!

Mustache is another templating solution that is actively being developed and it simplifies templates by combining conditional tags and enumeration tags. It also provides strong features like inverted sections, partials and high order sections with simple syntax. Mustache is also one of the fastest templating solutions See blog by Brian Landau. I, personally, find mustache a good templating solution since it has a simple syntax and performs well.

Mustache 是另一个正在积极开发的模板解决方案,它通过组合条件标签和枚举标签来简化模板。它还提供了强大的功能,例如具有简单语法的倒置部分、部分和高阶部分。Mustache 也是最快的模板解决方案之一,请参阅 Brian Landau 的博客。我个人认为 mustache 是一个很好的模板解决方案,因为它具有简单的语法并且性能良好。

回答by Juan Mendes

You should check out google closure template. It's completely independent so you can use it with any lib you want. It's a templating tool written in java.

您应该查看 google 关闭模板。它是完全独立的,因此您可以将它与您想要的任何库一起使用。这是一个用java编写的模板工具。

http://code.google.com/closure/templates/docs/helloworld_js.html

http://code.google.com/closure/templates/docs/helloworld_js.html

It allows you to create a template on the server, run a java "compiler" on it and the output is a javascript function that takes json as its parameter.

它允许你在服务器上创建一个模板,在它上面运行一个 java“编译器”,输出是一个以 json 作为参数的 javascript 函数。

{namespace examples}
/**
 * Greets a person using "Hello" by default.
 * @param name The name of the person.
 * @param? greetingWord Optional greeting word to use instead of "Hello".
 */
{template .helloName}
  {if not $greetingWord}
    Hello {$name}!
  {else}
    {$greetingWord} {$name}!
  {/if}
{/template}

This will generate a function called examples.helloName that can be called like

这将生成一个名为 examples.helloName 的函数,可以像这样调用

Their format is very IDE friendly, I get all the HTML syntax highlighting when editing the templates

它们的格式对 IDE 非常友好,我在编辑模板时会突出显示所有 HTML 语法

examples.helloName({name: 'Ana', greetingWord:"Howdy"});

You can call other templates from within templates, it automatically html escapes your data (unless you tell it not to), provides bidirection support.

您可以从模板中调用其他模板,它会自动 html 转义您的数据(除非您告诉它不要),提供双向支持。

Another great thing is the fact that the templating tool can also generate java code. So somebody writing an app that must support browsers with scripting disabled can generate the HTML on the server if necessary.

另一个很棒的事情是模板工具也可以生成 java 代码。因此,如果需要,编写必须支持禁用脚本的浏览器的应用程序的人可以在服务器上生成 HTML。

Last but not least, unlike other js templating systems (), the template is parsed on the server, so the client side only has to do the merging of the template and data, the parsing of the template is done as a build step on the server.

最后但并非最不重要的是,与其他 js 模板系统 () 不同,模板是在服务器端解析的,因此客户端只需要将模板和数据合并,模板的解析是作为构建步骤完成的服务器。

http://dev.sencha.com/deploy/dev/docs/?class=Ext.XTemplateis an example of a templating tool that runs completely on the client. There are two problems with this approach, the parsing of the template is done on the client and your html has to be embedded in a javascript string. However, some IDEs (Intellij) will highlight the HTML inside JS strings).

http://dev.sencha.com/deploy/dev/docs/?class=Ext.XTemplate是一个完全在客户端运行的模板工具的例子。这种方法有两个问题,模板的解析是在客户端完成的,你的 html 必须嵌入到 javascript 字符串中。但是,某些 IDE(Intellij)会突出显示 JS 字符串中的 HTML)。

回答by Jay

What about JAML Code?

JAML 代码呢?

http://github.com/edspencer/jaml

http://github.com/edspencer/jaml

Similar to a few of the above but I believe is a bit more logical...

类似于上面的一些,但我认为更合乎逻辑......

It is the concept of defining your templates via JSON / JavaScript and then using a function in JavaScript to pass arguments to your template which gets it rendered and returned as an element.

它的概念是通过 JSON / JavaScript 定义模板,然后使用 JavaScript 中的函数将参数传递给模板,模板将其呈现并作为元素返回。

There are implementations around for the various JavaScript Frameworks that exist.

存在各种 JavaScript 框架的实现。

回答by s4y

I have a templating engine called stencil.js, which I believe is pretty sweet. It works with jQuery via the jquery-haml DOM building engine.

我有一个名为 stencil.js 的模板引擎,我认为它非常棒。它通过jquery-haml DOM 构建引擎与 jQuery 一起使用。

Write your template (which you can put in an external file and decode as JSON):

编写您的模板(您可以将其放入外部文件并解码为 JSON):

["%div.sidebar_elem"
    ["%a", { href: { key:'link' } },
        { key: "text" }
    ]
]

And run it through stencilalong with your data:

stencil与您的数据一起运行它:

$("#parent").stencil(template, { link: "http://example.com", text: "Click me!" });

There are more examples at the stencil.jsGitHub project, but I think it's just what you're looking for.

stencil.jsGitHub 项目中有更多示例,但我认为这正是您要寻找的。

It could use a couple more utility methods, and some code for an unfinished data binding component is still in the masterbranch, so drop me a comment if you're interested and I'll see if I can clean it up.

它可以使用更多的实用方法,并且未完成的数据绑定组件的一些代码仍在master分支中,因此如果您有兴趣,请给我留言,我会看看是否可以清理它。

回答by Chris Holland

check out ibdom, and some background/history here: Recommended JavaScript HTML template library for JQuery?

在此处查看 ibdom 和一些背景/历史:为 JQuery 推荐的 JavaScript HTML 模板库?

回答by edwardsharp

Could always go with jQuery-Templates: http://api.jquery.com/category/plugins/templates/

总是可以使用 jQuery 模板:http: //api.jquery.com/category/plugins/templates/