golang- template (golang- template) (英语) 
类型脚本执行 跳转到模板 语法.
安装
npm install @ctrl/golang-template
使用量
import { compile, parse } from '@ctrl/golang-template';
// One-shot
parse('{{ if .keywords }}{{ .keywords }}!!{{ else }}nothing{{ end }}', { keywords: '123' });
// '123!!'
// Compile once, render many times (better for hot paths)
const tmpl = compile('{{ if .name }}Hello {{ .name }}!{{ end }}');
tmpl.render({ name: 'World' }); // 'Hello World!'
tmpl.render({ name: 'Alice' }); // 'Hello Alice!'
支持的语法
变量
parse('{{ .foo }}', { foo: 'bar' });
// 'bar'
parse('{{ .user.name }}', { user: { name: 'Alice' } });
// 'Alice'
如果/ 其它情况
parse('{{ if .keywords }}{{ .keywords }}{{ else }}nothing{{ end }}', { keywords: 'swag' });
// 'swag'
如果有和/或/没有
parse('{{ if and .a .b }}both{{ else }}no{{ end }}', { a: 'x', b: 'y' });
// 'both'
parse('{{ if or .a .b }}either{{ else }}neither{{ end }}', { a: '', b: 'y' });
// 'either'
parse('{{ if not .disabled }}enabled{{ end }}', { disabled: false });
// 'enabled'
与
设定 . 改为区块持续时间的值;如果区块值为虚构,则跳过区块.
parse('{{ with .user }}Hello {{ . }}!{{ end }}', { user: 'World' });
// 'Hello World!'
parse('{{ with .user }}Hello {{ . }}{{ else }}nobody{{ end }}', { user: '' });
// 'nobody'
范围
const categories = ['a', 'b', 'c'];
parse('{{ range .categories }}{{ . }};{{ end }}', { categories });
// 'a;b;c;'
const items = [{ name: 'alice' }, { name: 'bob' }];
parse('{{ range .items }}{{ .name }};{{ end }}', { items });
// 'alice;bob;'
内部 range, (中文(简体) ), {{ .Field }} 仅针对当前项目. {{ $.RootVar }} 仍然不支持.
指数
const data = {
object: { value: 'foo' },
array: ['bar'],
};
parse('{{ index .object "value" }}', data); // 'foo'
parse('{{ index .array 0 }}', data); // 'bar'
加入 {{}
const categories = ['a', 'b', 'c'];
parse('{{ join .categories "," }}', { categories });
// 'a,b,c'
替换( r)
parse('{{ re_replace .category "[^a-zA-Z0-9]+" "%" }}', { category: '123$special' });
// '123%special'
† 非标准扩展,在Go's没有 text/template。 。 。 .
兼容性
| 特性 | 支助 |
|---|---|
{{ .Variable }} | ✅ |
{{ .nested.path }} | ✅ |
{{ if }} 编号 : {{ else }} 编号 : {{ end }} | ✅ |
{{ if and .a .b }} 编号 : {{ if or .a .b }} 编号 : {{ if not .a }} | ✅ |
{{ with }} | ✅ |
{{ range }} 与 {{ . }} | ✅ |
{{ index .arr 0 }} 编号 : {{ index .obj "key" }} | ✅ |
{{ join }} (电话分机) | ✅ |
{{ re_replace }} (电话分机) | ✅ |
{{ range }} 与 {{ .Field }} 关于项目 | ✅ |
{{ if eq .a .b }} 编号 : {{ if gt .a .b }} 包括:. | ❌ |
{{ $var := .val }} 可变任务 | ❌ |
{{ $.RootVar }} 从内部范围/与 | ❌ |
{{ len .val }} | ❌ |
{{ printf }} 编号 : {{ html }} 编号 : {{ js }} | ❌ |
{{ template }} 编号 : {{ block }} | ❌ |
警告
不要完全不可信的模板 。 这个 re_replace tag运行模板提供的JavaScript regex模式,因此恶意或粗心的模式仍然会导致CPU使用过度.