Grails 3.1 JSON-Views,渲染类别树

时间:2016-03-02 05:01:10

标签: angularjs mongodb gson grails-3.1 json-view

我正在使用Graisl 3.1.1,rest-api配置文件。 我正在尝试构建一个类别树,但是我在使用JSON-Views渲染类别时遇到了一些问题。

我使用json模板,一个用于父级,另一个用于子级。 基本上我想生成像这样的角度的json:

angularjs Category treet

这是我的代码。

任何帮助?

Stacktrace

//域

class Category {
  ObjectId id /* MongoDB */
  static hasMany = [categories: Category]
  String name
  ...

//控制器

def directory(){
   def categories = Category.findAllByCategoriesIsNotNull([sort: 'name', order: 'asc'])
   respond categories
}

// directory.gson

import com.example.Category
model {
    Iterable<Category> categoryList
}
json {
  categories g.render(template: 'parent', collection: categoryList ?: [], var: 'category')
}

// _ parent.gson

import com.example.Category
model {
  Category category
}
json {
  id   category.id.toString()
  name category.name
  categories g.render(template: "category/child", collection: category.categories ?: [], var: 'child')
}

问题是上面的categories行,我不确定是什么问题或我的错误。

// _ child.gson

import com.example.Category
model {
  Category child
}
json {
  name child.name
}

2 个答案:

答案 0 :(得分:1)

我有理由相信你遇到了我几周前遇到的同一个新鲜的bug(在grails-views@1.0.4中修复),#9720

  

似乎g.render无法识别相对路径,即使模板与调用gson文件位于同一目录中,也需要完全限定路径。

而不是:

categories g.render(template: "category/child", collection: category.categories ?: [], var: 'child')

在模板前加斜杠:

categories g.render(template: "/category/child", collection: category.categories ?: [], var: 'child')

您可能还需要更改:

categories g.render(template: 'parent', collection: categoryList ?: [], var: 'category')

为:

categories g.render(template: '/category/parent', collection: categoryList ?: [], var: 'category')

答案 1 :(得分:-1)

我通常在控制器中使用

  

导入grails.converters.JSON

然后

  

将结果呈现为JSON