javascript mustache.js 中 compile()、parse() 和 render() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9384650/
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-26 06:30:07  来源:igfitidea点击:

Difference between compile(), parse(), and render() in mustache.js

javascripttemplatesmustache

提问by alnafie

What is the difference between:

有什么区别:

Mustache.compile(), Mustache.parse(), and Mustache.render()

Mustache.compile(), Mustache.parse(), 和 Mustache.render()

in the new mustache.jsversion 0.5.0, and perhaps for bonus points you could tell us what the difference between parsing and compiling is in general.

在新的mustache.js版本 0.5.0 中,也许为了奖励积分,您可以告诉我们解析和编译之间的一般区别。

回答by Tomalak

EDIT

编辑

With an API change introduced in version 0.8.0, the compile()method has been integrated into parse(). Manually compiling the templates is no longer required.

随着0.8.0 版中引入API 更改,该compile()方法已集成到parse(). 不再需要手动编译模板。



Mustache.parse()

Mustache.parse()

Syntactically parses the template and creates a JavaScript function body (a string) from it. During that process it notifies of any syntax errors encountered in the template.

从语法上解析模板并从中创建一个 JavaScript 函数体(一个字符串)。在该过程中,它会通知模板中遇到的任何语法错误。

Mustache.compile()

Mustache.compile()

Uses the function body returned from a successful parse()to create an actual JavaScript function. The created function is placed in a cache for re-use.

使用成功返回的函数体parse()创建实际的 JavaScript 函数。创建的函数被放置在缓存中以供重用。

Mustache.render()

Mustache.render()

Takes the appropriate function for a given template (the one that was created by compile()) and applies it to actual data. This creates the result meant to be shown on screen.

为给定的模板(由 创建的模板)获取适当的函数compile()并将其应用于实际数据。这将创建要在屏幕上显示的结果。

回答by Alireza Fattahi

Just a tip Mustache.parse(template)is optional and speeds up future uses of template. This is useful when you want to reuse your template with a set of (large) data. If this is not the case a call to the Mustache.render(), which generates the final result, is enough.

只是一个提示Mustache.parse(template)是可选的,可以加快模板的未来使用。当您想使用一组(大)数据重用模板时,这很有用。如果不是这种情况,则调用Mustache.render()生成最终结果的 就足够了。

回答by Shahar Shokrani

A little extra: If you working with custom delimiters (instead of {{and }}), you can use Mustache.parsebefore calling the Mustache.renderwith the custom delimiters as a parameter.

一点额外的:如果您使用自定义分隔符(而不是{{}}),则可以Mustache.parse在调用之前Mustache.render使用自定义分隔符作为参数。

Example:

例子:

var template = "<h1>Hello {{$name$}}</h1>"
var customTags = [ '{{$', '$}}' ];
Mustache.parse(template, cutomTags);
var result = Mustache.render(template, { name: "John" };
console.log(result);

Will result In:

将导致:

Hello John