数据模型与 JSON 桥接
仓颉无运行时反射,模板渲染的数据以显式代数类型 TemplateValue 建模,而非任意对象内省。
TemplateValue
cangjie
public enum TemplateValue {
| TStr(String)
| TInt(Int64)
| TFloat(Float64)
| TBool(Bool)
| TList(Array<TemplateValue>)
| TMap(HashMap<String, TemplateValue>)
| TNil
}顶层标量构造器与列表助手:
cangjie
tstr("hi") // TStr
tint(42) // TInt
tfloat(3.14) // TFloat
tbool(true) // TBool
tlist([tstr("a"), tint(1)]) // TList
tstrList(["a", "b", "c"]) // 字符串数组 → TList<TStr>TemplateModel(链式构造器)
对象模型用 TemplateModel 链式构造,set 有多个重载(String/Int64/Bool/Float64/TemplateValue):
cangjie
let model = TemplateModel()
.set("name", "Ada")
.set("age", 36)
.set("vip", true)
.set("tags", tstrList(["web", "macro"]))
.value() // 收敛为 TemplateValue(TMap),交给 renderengine.render(name, model) / renderString(src, model) 同时接受 TemplateModel 与 TemplateValue(TemplateModel 有便捷重载)。
嵌套对象:把子 TemplateModel().value() 作为字段:
cangjie
let addr = TemplateModel().set("city", "Paris").value()
let user = TemplateModel().set("name", "Ada").set("addr", addr).value()
// 模板中 {{ user.addr.city }}列表 of 对象:
cangjie
let rows = TList([
TemplateModel().set("n", "Ada").set("age", 36).value(),
TemplateModel().set("n", "Al").set("age", 24).value()
])
let model = TemplateModel().set("users", rows)
// 模板 {{#users}}<li>{{ n }}:{{ age }}</li>{{/users}}JSON 桥接(jsonToTemplateValue)
integration 层提供 jsonToTemplateValue,把 JSON 文本直接转成 TemplateValue——ORM/接口的 JSON 响应可零胶水喂进模板:
cangjie
import ace_template.*
let json = "{\"name\":\"cangjie kit\",\"price\":128,\"tags\":[\"web\",\"orm\"]}"
let product = jsonToTemplateValue(json)
let model = TemplateModel().set("product", product)
return renderView(ctx, engine, "product", model)html
<h2>{{ product.name | upper }}</h2>
<p>价格:{{ product.price }}</p>
<ul>{{#product.tags}}<li>{{@number}}. {{ . }}</li>{{/product.tags}}</ul>映射规则:对象→TMap、数组→TList、字符串→TStr、整数→TInt、小数→TFloat、布尔→TBool、null→TNil。整数与小数由底层 stdx JSON DOM 天然区分。非法 JSON 抛 TemplateException。
桥接基于框架
ace_framework_runtime.parseJson(底层stdx.encoding.json),位于integration子包;纯engine子包不触 stdx,保持可离线单测。