最終的なHTMLの出力で内容が存在しないときは、そもそもその属性そのものを出力したくないということがある。
<link rel="alternate" type="application/atom+xml" href="/docs/feed.xml" title="hbsnow.github.io/docs">
この例ではtitle属性があるんだけれども、これが空になると
<link rel="alternate" type="application/atom+xml" href="/docs/feed.xml" title="">
これでは少し気持ちが悪いので
<link rel="alternate" type="application/atom+xml" href="/docs/feed.xml">
上記のようにしたいということ。
ユーザ入力がないのであれば、素直に &attributes
を使えばいい。
attributes.pug
-
var feed = {
href: '/docs/feed.xml'
}
if feed && feed.hasOwnProperty('href')
link(rel='alternate' type='application/atom+xml')&attributes(feed)
output.html
<link rel="alternate" type="application/atom+xml" href="/docs/feed.xml">
そうでない場合にはサニタイズしろ、みたいなことが公式に書いてあるんだけど、とくにそれをやってくれるようなヘルパーみたいなものもないので、recursive-escapeなどでエスケープするか、それが難しいのであれば、あとは酷いけれども泥臭いmixinを書くしかないような気もするんだけど
mixin.pug
mixin atom(feed)
- var hasFeed = feed && feed.hasOwnProperty('href')
if hasFeed && feed.hasOwnProperty('title')
link(rel='alternate' type='application/atom+xml' href=feed.href title=feed.title)
else if hasFeed
link(rel='alternate' type='application/atom+xml' href=feed.href)
+atom(feed)
さすがにこんなものは現実的ではないので、ちゃんとエスケープして &attributes
を使うってのが唯一の解決策のような気がする。他になにかいい方法があれば知りたい。