在R中制作Quarto PDF的Typst模板:矩形渲染问题及转写咨询
问题描述
我正在用Typst为R中的Quarto PDF制作模板,以下是在Typst软件里能正常运行的代码:
#place( top + left, dx: 0pt, dy: -20pt, rect(fill: rgb("FA8975FF"), width: 0.15cm, height: 1cm), ) #place( top + left, dx: -5pt, dy: -10pt, rect(fill: rgb("000000"), width: 100%, height: 0.05cm), )
但把这段逻辑放到R对应的.typ模板文件里时,渲染完全异常,我的.typ代码如下:
#let psc-report( title: "title", body, ) = { // This sets the text for the entire document set text( font: "Calibri", size: 10pt, ) // This sets the paging formats set page( "us-letter", margin: ( left: 1in, right: 1in, top: 1in, bottom: 1in ), background: [ place( top + left, dx: 5pt, rect( fill: rgb("FA8975FF"), width: 0.25cm, height: 1cm ) ), place( top + left, dx: 10pt, rect( fill: rgb("15397F"), width: 100%, height: 0.1cm ) ) ], // not entirely sure how the footer page number works yet footer: align( grid( columns: (40%, 60%), align( horizon, text(fill: rgb("15397F"), size: 10pt, counter(page).display("1") ) ), ) ) ) body }
请问:
- 如何在R的Typst模板中正确放置两个相邻矩形?
- 是否有Typst格式转R模板的相关指南?
解决方案
1. 修复相邻矩形渲染问题
核心问题是page的background参数中用方括号[]包裹内容时,Typst会将其视为流式内容,place的页面锚点定位逻辑失效。需将方括号替换为代码块大括号{},让定位逻辑在代码上下文执行。
修改后的page配置代码:
set page( "us-letter", margin: ( left: 1in, right: 1in, top: 1in, bottom: 1in ), background: { place( top + left, dx: 0pt, dy: -20pt, rect( fill: rgb("FA8975FF"), width: 0.15cm, height: 1cm ) ), place( top + left, dx: -5pt, dy: -10pt, rect( fill: rgb("000000"), width: 100%, height: 0.05cm ) ) }, footer: align( grid( columns: (40%, 60%), align( horizon, text(fill: rgb("15397F"), size: 10pt, counter(page).display("1") ) ), ) ) )
关键调整:
- 把
background: [ ... ]改为background: { ... },确保定位基于页面锚点生效 - 对齐
dx、dy参数和Typst原生测试代码,保证位置和原生环境一致
2. Typst转R Quarto模板的注意事项
目前没有专门的转格式指南,但需注意Quarto中Typst模板的运行逻辑:
- 模板以自定义函数形式运行(如
psc-report),所有页面配置、元素定位必须放在函数体内部 - 页面的
background、header、footer需用代码块{}包裹内容,流式内容[]会导致定位、尺寸逻辑失效 - 函数内部先设置全局样式(如
set text),再配置页面(set page),最后返回body - 移植时先在Typst原生环境验证单个元素样式和定位,再逐步整合到Quarto模板函数中调整参数
内容的提问来源于stack exchange,提问作者M.Frumh
相关产品推荐
相关产品推荐

