在Grails应用程序中,导航菜单是特定于客户端的,并以JSON形式返回到SPA。我们需要将这些菜单配置存储为可人工编辑的文件,以便它们易于维护和在客户端之间进行区分(不需要扩展,因为我们谈论的定制菜单少于10个)。
如果它是完全静态的,我们可以简单地使用JSON文件并完成它。
[
"id": 1,
"text": "Menu Item 1",
"children": [...],
, ...
]
但是,有一些最小的动态元素,我很好奇是否有像HTML那样的JSON模板库。
[{
"for": "user in users"
"userId": {{user.id}}
"text": "Nav Item 1",
"children": [
{
"parentUserId": {{user.id}}
"text": "Child Nav Item"
}
]},
, {...}, ...
]
输出:
[{
"userId": "bob"
"text": "Nav Item 1",
"children": [
{
"parentUserId": "bob"
"text": "Child Nav Item"
}
]
}, {
"userId": "admin"
"text": "Nav Item 1",
"children": [
{
"parentUserId": "admin"
"text": "Child Nav Item"
}
]
}
]
因此,基本上的要求是重复深层JSON对象(例如angular的ng-repeat)并允许变量替换。如果仅读取有效的JSON字符串并在其上运行类似FreeMarker的内容,则变量替换将很容易,但是某些变量值可能是数字。
另外,由于我们使用的是Groovy / Grails,所以我们也可以将菜单存储为Groovy配置文件(尽管我还是不太确定如何用Groovy完成该菜单)。
如果您有任何想法,我也欢迎其他选择。
最佳答案
在处理json文件之前,您可以将其视为groovy template:
def text = '''[
{
"id": 1,
"description": "Home",
},
{
"id": 2,
"description": "Receipts",
"children": [
{
"id": 3,
"description": "$receiptChild"
}
]
}
]'''
def engine = new groovy.text.SimpleTemplateEngine()
def data = [receiptChild: 'List all']
def template = engine.createTemplate text make data
def json = new groovy.json.JsonSlurper().parseText template.toString()
assert json[1].children[0].description == 'List all'
之后,您可以正常将其读取为json文件。
关于json - JSON模板库-将动态元素添加到静态JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38485761/