LoginSignup
10
7

More than 5 years have passed since last update.

Railsでhtml template内のJSON-LDをjbuilderを使って楽に書く

Posted at

例えばslim, jbuilder環境だとして

$ tree app/views
app/views
├── users
│   └── show.html.slim
└── schemas
    └── person.json.jbuilder

というファイル構成の場合に

users/show.html.slim
script type="application/ld+json"
  /escapeされてしまうので、`==`でraw出力
  == render partial: 'schemas/person.json', locals: { name: 'damele0n' }
schemas/person.json.jbuilder
# json.@contextのようには記述できないので、`set!`を用いてSymbolで指定する
json.set! :@context, 'http://schema.org/'
json.set! :@type, 'Person'
json.name name

のように、partial templateとしてjbuilderで記述したtemplateを呼び込むとある程度楽に記述できる。


※script内でraw出力しているので、間違った指定やtemplateをrenderすると簡単にXSSを起こせるので注意すること

10
7
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
10
7