11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Riotでnl2br

Posted at

改行の入った長い文字列を表示するとなれば、PHPでいうnl2br()、Railsのsimple_formatのような、「改行文字を<br>タグに置き換えて表示」という処理がしたくなるものです。ただ、Riot標準では、そういう機能はなさそうです。

もちろん、RiotでもinnerHTMLに代入するような荒技を取れば、JavaScriptで生成したHTMLも、そのまま反映させることができます。ただ、そのようなコーディングをやっていると、XSSの危険もあるので、できれば避けたいものです。ということで、「Riot的に」<nl2br>タグを作ってみましたs。

実際のタグ

nl2br.tag
<nl2br>
  <virtual each={text, i in texts}>
    <br if={i}>{text}
  </virtual>

  this.texts = opts.text.split('\n')
</nl2br>

jsFiddleでの動作サンプル

動作内容

まずは、受け取ったテキストをsplitで改行ごとに区切って、配列にします。そして、<virtual>タグでeachさせて1つずつ出力していきますが、最初以外では出力の直前に<br>を入れることで、「もとの改行の位置に<br>を入れる」という処理となります。

11
4
1

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
11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?