You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny/bslib中让JSON生成的卡片水平每行排列4个?

解决bslib应用中产品卡片水平每行排列4个的问题

问题原因

当前代码里,layout_column_wrap直接接收cards_list这个列表作为参数,但该函数需要逐个传入卡片元素,而非一个包含所有卡片的列表。直接传入列表会被当作单个元素处理,导致卡片垂直堆叠。

解决方案

使用rlang包的!!!(展开操作符)将cards_list中的每个卡片元素单独传入layout_column_wrap,就能实现每行4个卡片的水平布局。

修改后的完整代码

library(bslib)
library(jsonlite)
library(shiny)
library(glue)
library(bsicons)
library(rlang) # 加载rlang包以使用!!!操作符

# Product List (后续可迁移至可编辑JSON文件)
products <- list(
  "p1" = list(
    title = "P1",
    icon = "pie-chart",
    info = "This is Product 1"
  ),
  p2 = list(
    title = "P2",
    icon = "book",
    info = "This is Product 2"
  ),
  p3 = list(
    title = "P3",
    icon = "bar-chart",
    info = "This is Product 3"
  ),
  p4 = list(
    title = "P4",
    icon = "graph-up",
    info = "This is Product 4"
  ),
  p5 = list(
    title = "P5",
    icon = "gear",
    info = "This is Product 5"
  )
)

# 生成产品卡片的函数
produce_card <- function(card_config) {
  title <- card_config[["title"]]
  icon <- card_config[["icon"]]
  info <- card_config[["info"]]

  card(
    card_header(title, class = "fs-5 bg-primary"),
    card_body(
      value_box(
        title,
        value = info,
        showcase = bs_icon(icon)
      )
    ),
    max_height = "50%"
  )
}

# 生成卡片列表
cards_list <- lapply(products, produce_card)

# Shiny应用UI
ui <- page_navbar(
  title = "Product Catalogue",
  bg = "purple",

  nav_panel(
    title = "Catalogue",
    icon = bs_icon("journal-bookmark-fill"),
    align = "right",
    layout_column_wrap(
      width = 0.25, # 每个卡片占1/4宽度,对应每行4个
      !!!cards_list # 用!!!展开列表中的每个卡片元素
    )
  )
)

server <- function(input, output, session) {
}

shinyApp(ui, server)

补充说明

  • width = 0.25设置每个卡片占据父容器1/4的宽度,刚好实现每行4个卡片的布局
  • 额外添加了3个产品示例,便于验证多行排列的效果
  • 必须加载rlang包,!!!操作符依赖该包完成列表展开操作

内容的提问来源于stack exchange,提问作者Supratik C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:43:17