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

与世无争的帅哥 提交于 2019-12-22 03:50:54

问题


What is the difference between:

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

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


回答1:


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.


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.

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.

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.




回答2:


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.




回答3:


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

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


来源:https://stackoverflow.com/questions/9384650/difference-between-compile-parse-and-render-in-mustache-js

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