如何从pug传递数组到pug混合器?

3
我有一个包含数组的pug模板,我想将其传递给一个mixin,用于填充一些schema.org(json)标记。
以下是代码: profile.pug
include ../components/bio-seo

- var person = {}
- person.title = "Name, title of person"
- person.url = "https://page.url..."
- person.image = "https://images.url..."
- person.links = ["https://link.one...","https://link.two..."]

+bio-seo(person)

然后在mixin中,我有:
mixin.pug
mixin bio-seo(person)
  title= title
  link(rel='canonical', href=url)

  script(type="application/ld+json").
    {
      "@context": "http://schema.org",
      "@type": "Person",
      "image": "#{person.image}",
      "url": "#{person.url}",
      "sameAs": #{person.links}
    }

一切都很好,除了“sameAs”链接的数组。编译后,我得到:
"sameAs": https://link.one,https://link.two

我需要的不是这个,而是...
"sameAs": ["https://link.one","https://link.two"]

顺便说一下,这全部都落在HTML文档的头部。 - Costa Michailidis
“sameAs”: [!{person.links.map(link => '“' + link.toString() + '”')}] 这看起来可以工作,但...该死!我真的需要所有这些吗? - Costa Michailidis
这是我知道的最简洁的方法。 - Sean
为什么不能直接写成 !{person.links} 或者 person.links 呢? - Costa Michailidis
1
!{...} is unescaped string interpolation, and it just prints the values of whatever it contains as a string. Array markup (brackets, quotes) isn't part of the value of the array.Whenever I have to use js like this, I like to write it as a function using a code block in a separate .pug file. That way you can just include your functions file and keep your pug cleaner by writing something like printArray(person.links) - Sean
1个回答

3
您可以使用JSON.stringify非转义插值!{}结合使用,将您的数组转换成字符串:
"sameAs": !{JSON.stringify(person.links)}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接