【麦芽糖】Rails Jbuilder 模板渲染

1. 渲染成散列,单个 partial 的引用

json.partial!'project', project: @project
# => {}

1.1 在散列 partial 外套一层

json.project do
  json.partial! 'project', project: @project, full: true # 单个散列的传参
end
# => 格式如下
{
  "project": {
    "id": 1,
    "picture": null,
    "created_at": "2019-04-22 07:48:27 UTC",
    "published": true,
    "name": "测试项目01",
    "purpose": "我是立项目的",
    "stage": "立项中",
    "industrial_level": "中试"
  }
}

2. 渲染成数组

json.array! @projects, partial: 'project', as: :project
# => [{}, {}]

json.partial! 'project', collection: @projects, as: :project
# => [{}, {}]

json.partial! partial: 'project', collection: @projects, as: :project
# => [{}, {}]

注:
以上写法传参语法不同,详见下方

2.2 在数组外套一层

json.projects do
  # 传递参数 full: true
  json.array! @projects, partial: 'project', as: :project, locals: { full: true }
  json.partial! 'project', collection: @projects, as: :project, full: true
  json.partial! partial: 'project', collection: @projects, as: :project, locals: { full: true }
end

json.projects @projects, partial: 'project', as: :project, locals: { full: true }

# => 格式如下
{
  "page_info": {
    "total_items": 53,
    "total_pages": 6
  },
  "projects": [{},{}]
}

其他:

  • 在 partial 中获取当前参数
local_assigns
local_assigns.class # => Hash (知道这是一个散列,就随便你怎么玩啦)
local_assigns.keys  # => [:project, :full, :json]

  • 官方文档
    https://github.com/rails/jbuilder
  • 创建时间
    2019年06月27日13:12:45

你可能感兴趣的:(【麦芽糖】Rails Jbuilder 模板渲染)