Nodejs中Logicless template对应什么样的应用场景?
Nodejs中Logicless template对应什么样的应用场景?
今天搜索一堆模板的时候注意到还有这个术语, 就搜了下: The Case Against Logic-less Templates What’s the advantage of Logic-less template (such as mustache)? Cult of Logic-Less Templates mustache – Logic-less templates 然后… 英文都好难懂啊
比如 Mustache, 移除了 for if
等等语句,
用变量的值直接表示 if
执行的逻辑:
Shown.
{{#nothin}}
Never shown!
{{/nothin}}
以及自动对数据进行替换: Template:
{{#repo}}
<b>{{name}}</b>
{{/repo}}
Hash:
Data:
{
"repo": [
{ "name": "resque" },
{ "name": "hub" },
{ "name": "rip" },
]
}
Output:
<b>resque</b>
<b>hub</b>
<b>rip</b>
或者更花哨一些的, 其实还是在实现 ejs 里的 for if
等等功能,
这样的方案看不出这个取舍带来特别的好处啊,
仅仅是模板的性能提升么? 但最快的 doT 也是能潜入 JS 代码的呀?
或者说 Logicless template 适用什么样的场景, Node 社区里会这么热?
我觉得 Logic-less templates 也就是如同其字面意思吧。 在模板里码上一堆逻辑,有点混乱了,本身模板就是为了解决数据渲染的,而并不解决逻辑处理吧,况且维护会很痛苦的。
话说,undersocre 那个模板引擎有用过没…?
就玩了下,看评测效率不是很高,除了引入外部代码的体积以外没发现特别的优势啊。
Node.js中的Logicless Template(无逻辑模板)通常用于需要分离视图层与业务逻辑的应用场景。这种模板引擎强制将所有的逻辑处理放在后端服务中完成,从而使得模板本身只负责展示数据。这种方式有助于保持模板的清晰和易于维护,并且可以更好地支持前端工程师专注于UI开发,而后端工程师则专注于业务逻辑。
例如,Mustache是一个典型的无逻辑模板引擎,它不支持条件判断、循环等逻辑语句,所有这些都需要在服务端预先处理好,再传递给模板引擎进行渲染。
以下是一个简单的Node.js + Mustache的例子:
const mustache = require('mustache');
const fs = require('fs');
// 数据源
const data = {
repo: [
{ name: 'resque' },
{ name: 'hub' },
{ name: 'rip' },
],
nothing: false,
};
// 模板字符串
const template = `
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^nothing}}
This will not be displayed.
{{/nothing}}
`;
// 渲染模板
const rendered = mustache.render(template, data);
console.log(rendered);
在这个例子中,我们使用了{{#repo}}
和{{/repo}}
来遍历data.repo
数组,而{{^nothing}}
和{{/nothing}}
则用来检查data.nothing
的布尔值是否为false
。通过这种方式,我们可以确保所有的逻辑都在服务端处理完成,模板本身只需要关注如何展示数据即可。
这种方式非常适合于团队协作,特别是当后端和前端的职责明确时,能够提高开发效率并降低维护成本。