LoginSignup
0
0

More than 5 years have passed since last update.

pugで存在しない可能性のある属性を出力する

Last updated at Posted at 2017-11-16

最終的な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 を使うってのが唯一の解決策のような気がする。他になにかいい方法があれば知りたい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0