如何根据数组长度自动调整Student/Supervisor等词汇的单复数
问题解决:根据数组长度自动切换单复数并修正语法错误
核心问题分析
你的代码主要存在三个问题:
- 条件分支语法错误:在
stack子元素中使用if语句时,分支结构和逗号位置不符合Typst语法规则,导致解析失败。 - 空数组处理缺失:
supervisors和co-supervisors为空时仍会显示标题,不符合需求。 - 变量名语法冲突:
co-supervisors和co-supervisor中的连字符会被Typst解析为减法运算,需调整命名格式。
修正后的完整代码
grid( columns: 2, column-gutter: if authors.len() > 20 { 3em } else { 7em }, // authors至少有一个元素,无需重复判断len()>0 // Students列 stack( dir: ttb, spacing: 0.7em, // 根据authors长度切换单复数标题并渲染内容 if authors.len() > 1 { align(start, emph("Students:")), ..authors.map(author => align(start, author)) } else { align(start, emph("Student:")), align(start, authors.first()) }, ), // Supervisors和Co-Supervisors列 stack( dir: ttb, spacing: 0.7em, // 非空时才渲染Supervisors区块,自动切换单复数 if supervisors.len() > 0 { align(start, emph(if supervisors.len() > 1 { "Supervisors:" } else { "Supervisor:" })), ..supervisors.map(supervisor => align(start, supervisor)), }, // 非空时才渲染Co-Supervisors区块,修正变量名避免语法冲突 if co_supervisors.len() > 0 { align(start, emph(if co_supervisors.len() > 1 { "Co-Supervisors:" } else { "Co-Supervisor:" })), ..co_supervisors.map(co_supervisor => align(start, co_supervisor)), }, ), )
关键修正点说明
- 简化列间距逻辑:利用
authors至少有一个元素的前提,去掉多余的len()>0判断。 - 空数组过滤:对
supervisors和co_supervisors增加非空判断,为空时不渲染对应区块。 - 动态单复数切换:所有标题都根据对应数组长度自动选择单复数形式,覆盖Student、Supervisor、Co-Supervisor三类场景。
- 变量名修复:将
co-supervisors改为co_supervisors,co-supervisor改为co_supervisor,避免连字符引发的语法错误。 - 语法结构优化:调整
stack内条件分支的格式,确保元素列表的逗号分隔符合Typst语法要求。
内容的提问来源于stack exchange,提问作者Sumsar
相关产品推荐
相关产品推荐

