0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Markdownのtableで行見出しを書きたい

Posted at

Markdownのtableには「列見出し」しかない

Markdownにはいくつか方言があるのですが、ぼくの観測範囲では、thead > thは書けても、いわゆる「行見出し」を書ける記法が見つかりませんでした(見た目だけ見出しっぽくする方法はいくらかある)。

ので、michelf/php-markdownをオーバライドして、行見出しを書けるようにするcomposerを作りました。

以下のようなMarkdown記法で行見出しにします。

| Header 1 | Header 2 |
|----------|----------|
| Row 1   :| Cell 1   |
| Row 2   :| Cell 2   |

セルの末尾に:を付与します1

composerの使い方

composer require jidaikobo/php-markdown

上記コマンドで、vendorに必要なファイル群が入ります。

require 'vendor/autoload.php';

use Jidaikobo\MarkdownExtra;

$table = "
| Header 1 | Header 2 |
|----------|----------|
| Row 1   :| Cell 1   |
| Row 2   :| Cell 2   |
";

$html = MarkdownExtra::defaultTransform($table);

echo $html;

出力されるものは以下のとおりです。

<table>
<thead>
<tr>
  <th scope="col">Header 1</th>
  <th scope="col">Header 2</th>
</tr>
</thead>
<tbody>
<tr>
  <th scope="row">Row 1</th>
  <td>Cell 1</td>
</tr>
<tr>
  <th scope="row">Row 2</th>
  <td>Cell 2</td>
</tr>
</tbody>
</table>

table以外のMarkdown記法はPHP Markdown Extraのままです。

おまけ: captionも書きたい

最後の行で、|:で開始すると、captionになります。

| Header 1 | Header 2 |
|----------|----------|
| Row 1   :| Cell 1   |
| Row 2   :| Cell 2   |
|:capt.

以下が出力されます。

<table>
<caption>capt.</caption>
<thead>
<tr>
  <th scope="col">Header 1</th>
  <th scope="col">Header 2</th>
</tr>
</thead>
<tbody>
<tr>
  <th scope="row">Row 1</th>
  <td>Cell 1</td>
</tr>
<tr>
  <th scope="row">Row 2</th>
  <td>Cell 2</td>
</tr>
</tbody>
</table>
  1. なるべくそのまま見ても違和感が少ない記法にしたつもりですが、目立ち方が弱いかもしれません。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?