@uking/marmot
v2.0.1
Published
A lightweight and fast javascript native template rendering engine that supports browsers, FibJS and NodeJS.
Maintainers
Readme
@uking/marmot
一个轻量、快速的“字符串级”模板渲染引擎:不依赖 DOM,不需要虚拟 DOM,直接把模板渲染成 HTML 字符串,适合在 Node.js / 浏览器 / FibJS 等环境中做服务端渲染(SSR)或生成静态 HTML。
安装
npm i @uking/marmot
# or
yarn add @uking/marmot
# or
pnpm add @uking/marmot特性
- 原生模板字符串(tagged template)+ HTML 字符串输出
- 组件机制:组件嵌套、组件 props 合并
- 插槽:默认插槽与具名插槽(
Slot/Template) - 指令:
v-if/v-else-if/v-else/v-for - 插值:
{{ expression }} - 属性绑定:
:attr="expression"(支持 boolean / array / object) :class支持字符串 / 数组 / 对象写法
快速开始
import { html, render } from '@uking/marmot'
const out = render(html`
<div class="hello">Hello {{name}}</div>
`, {}, { name: 'marmot' })
console.log(out)使用方法(组件 + 插槽 + 指令)
marmot 的核心是三件事:
html`...`:创建一个模板节点(只允许“纯静态模板”)Component:通过data()/functions()/components()/render()描述组件render(node, components, data, context, slots):把模板渲染成字符串
1) 组件与插槽
import { html, render, Component } from '@uking/marmot'
class Layout extends Component {
render() {
return html`
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>{{title}}</title>
<Slot name="header" />
</head>
<body>
<Slot />
</body>
</html>
`
}
}
class Page extends Component {
components() {
return { Layout }
}
data() {
return {
list: ['a', 'b', 'c'],
cls: 'is-red'
}
}
render() {
return html`
<Layout title="Demo">
<Template slot="header">
<style>.is-red{color:red}</style>
</Template>
<h1 :class="cls">Hello</h1>
<ul>
<li v-for="item in list">{{item}}</li>
</ul>
</Layout>
`
}
}
const output = render(html`<Page />`, { Page })
console.log(output)2) v-if / v-else-if / v-else
import { html, render } from '@uking/marmot'
const output = render(
html`
<div>
<p v-if="ok">OK</p>
<p v-else>NOT OK</p>
</div>
`,
{},
{ ok: true }
)
console.log(output)3) v-for(数组 / 对象 / 数字范围)
import { html, render } from '@uking/marmot'
console.log(
render(html`<span v-for="n in 3">{{n}}</span>`)
)
console.log(
render(
html`<div v-for="(v, k) in map">{{k}}={{v}}</div>`,
{},
{ map: { a: 1, b: 2 } }
)
)表达式与上下文
{{ ... }}与:attr="..."里写的都是 JavaScript 表达式。- 表达式的变量来自
data(渲染数据)。 context会以__c变量注入到表达式里(用于跨组件传递上下文)。
示例:
import { html, render } from '@uking/marmot'
const output = render(
html`<div>User: {{__c.user.name}}</div>`,
{},
{},
{ user: { name: 'Alice' } }
)
console.log(output)注意事项
- 组件名必须以大写字母开头(用于区分普通标签与组件)。
- 组件名不能是
Template/Slot/Component。 html`...` 不支持模板字符串插值${...}(一旦传入动态值会抛错)。请把动态内容放到data/context,并用{{}}或:attr表达式读取。- 表达式通过
new Function执行,不要对不可信模板/数据开放任意表达式能力。
