如何在Rmd中的YAML元数据中创建三级对象?

时间:2017-11-02 10:44:29

标签: r r-markdown pandoc

我找到了一个很好的例子,说明如何在YAML元数据here中创建两级对象。例如,为了包含多个作者

---
title:  'This is the title: it contains a colon'
author:
- name: Author One
  affiliation: University of Somewhere
- name: Author Two
  affiliation: University of Nowhere
---

然后在html template

$for(author)$
$if(author.name)$
$author.name$$if(author.affiliation)$ ($author.affiliation$)$endif$
$else$
$author$
$endif$
$endfor$

是否可以在YAML中创建三级对象?例如,我想拥有来自同一机构的多位作者。因此,我的逻辑是

---
title:  'This is the title: it contains a colon'
author:
  - affiliation: 
     - name: Author One
       email: fake@fake.com
     - name: Author Two
       email: fake2@fake.com
  - affiliation: 
     - name: Author Three
       email: fake3@fake.com
---

但它不起作用。有可能吗?我知道它看起来没有任何意义,但对于我的html template结构来说它是必要的。

感谢您的帮助!

更新

我还添加了一个我在html template中创建的块。

$if(author)$
$for(author)$
<div class = "author-section">
<div>$author.affiliation$</div>
<div class = "authors">
$for(author.affiliation)$
<div class = "author">
<div class = "mid-col">
$author.affiliation.name$
</div>
<div class = "right-col">
<a>$author.affiliation.email$</a>
</div>
</div>
$endfor$
</div>
</div>
$endfor$
$endif$

然后,它工作正常,除了在我的YAML中没有值的$author.affiliation$。因此,在渲染之后,我得到了真实的&#34;我最后的.html文件中的字符串。

然而,当我在YAML中添加一个肯定词时,例如

author:
  - affiliation: University of Somewhere
     - name: Author One
       email: fake@fake.com

渲染过程中出现错误

Error in yaml::yaml.load(string, ...) : 
  Scanner error: mapping values are not allowed in this context at line 9, column 19

1 个答案:

答案 0 :(得分:3)

就个人而言,我会在第一个例子中保留原样。您可以为两位不同的作者写两次相同的联属名称。

但是,如果您真的想通过大学将YAML写入分组/嵌套作者,它看起来就像这样(如果您熟悉JSON,请尝试在线YAML到JSON转换器):

title:  'This is the title: it contains a colon'
university:
  - label: University of Somehwere
    author:
     - name: Author One
       email: fake@fake.com
     - name: Author Two
       email: fake2@fake.com
  - label: University of Nohwere
    author:
     - name: Author Three
       email: fake3@fake.com

然后pandoc模板循环看起来像这样:

$for(university)$
<div>
  $university.label$
  $for(university.author)$
    $university.author.name$
    <span class="">$university.author.email$</span>
  $endfor$
</div>
$endfor$