1

我有一些降价文件,我想将它们显示在我由 Laravel 开发的博客上。

所以我想出了这样一个解决方案:

控制器

public function display() {
    $pd = new Parsedown();
    $text = Storage::disk('local')->get('x.md');
    $html = $pd->text($text);
    $title = "title";
    return view('x.y', [
        "html" => $html,
        "title" => $title
    ]);
}

<div class="container-fluid">
    <div class="row">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title text-center">{{ $title }}</h3>
            </div>
            <div class="panel-body">
                {!! $html !!}
            </div>
        </div>
    </div>
</div>

它运行良好,除了table元素:

Parsedown像这样解析表:

header 1 | header 2
-------- | --------
cell 1.1 | cell 1.2
cell 2.1 | cell 2.2

进入:

<table>
<thead>
<tr>
<th>header 1</th>
<th>header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>cell 1.1</td>
<td>cell 1.2</td>
</tr>
<tr>
<td>cell 2.1</td>
<td>cell 2.2</td>
</tr>
</tbody>
</table>

然后我得到了一张没有引导样式的表,看起来很奇怪。我想要得到的是:

<table class="table">
  ...
</table>

那么,有人可以给我一些建议吗?

4

2 回答 2

2

在我阅读了 Parsedown 的源代码后,我找到了解决方案。

blockTable()方法:

改变这个:

        $Block = array(
            'alignments' => $alignments,
            'identified' => true,
            'element' => array(
                'name' => 'table',
                'handler' => 'elements'
            ),
        );

至:

        $Block = array(
            'alignments' => $alignments,
            'identified' => true,
            'element' => array(
                'name' => 'table',
                'handler' => 'elements',
                'attributes' => [       //+
                    "class" => "table"  //+
                ]                       //+
            ),
        );

它将输出table带有class="table".

最后,我创建了一个新类 extends ,并用我自己的实现Parsedown覆盖了该方法。blockTable

于 2017-09-21T14:20:13.007 回答
1

Parsedown不支持添加class到生成的元素。Parsedown也不支持将生成的 HTML 作为 XML 文档发出。因此,您有两个选择:

  1. 用于preg_replace替换为正则表达式。
  2. 使用SimpleXML(或类似方法)解析 HTML 树并替换元素。

由于 HTMLParsedown生成简单、格式正确且可预测,因此您可能会摆脱preg_replace. 实现看起来像这样:

public function display() {
    $pd = new Parsedown();
    $text = Storage::disk('local')->get('x.md');
    $html = $pd->text($text);
    $html = preg_replace('/^\s*<table>\s*$/', '<table class="table">', $html);
    $title = "title";
    return view('x.y', [
        "html" => $html,
        "title" => $title
    ]);
}
于 2017-09-21T13:54:04.967 回答