`,顶层块之间用 `
` 分隔。
*
* 用于嵌在句子中间的内容(脚注 sidenote):块级元素落进 `` / `` 里,浏览器会提前闭合外层,
* 把 sidenote 的结构切断、吞掉后面的正文。
*/
public function inlineSafe(Document $document, RenderContext $ctx): string
{
$previous = $this->inlineOnly;
$this->inlineOnly = true;
try {
if ($document->inline) {
return $this->document($document, $ctx);
}
$blocks = array_map(fn (Node $node) => $this->nodes([$node], $ctx), $document->nodes);
$html = implode('
', array_filter($blocks, fn (string $html) => $html !== ''));
return $html === '' ? '' : "{$html}";
} finally {
$this->inlineOnly = $previous;
}
}
/**
* @param list $nodes
*/
public function nodes(array $nodes, RenderContext $ctx): string
{
$html = '';
foreach ($nodes as $node) {
$html .= match (true) {
$node instanceof Text => e($node->value, false),
$node instanceof Element => $this->element($node, $ctx),
$node instanceof Call => $node->template->html($node, $ctx),
default => '',
};
}
return $html;
}
private function element(Element $element, RenderContext $ctx): string
{
$attrs = '';
foreach ($element->attrs as $name => $value) {
if ($name === 'src' && str_starts_with($value, '/') && ! str_starts_with($value, '//')) {
$value = rtrim((string) config('app.url'), '/').$value;
}
$attrs .= ' '.$name.'="'.e($value, false).'"';
}
if ($this->inlineOnly && in_array($element->tag, self::BLOCK_TAGS, true)) {
if ($element->tag === 'hr') {
return '
';
}
$class = 'md-'.$element->tag.(isset($element->attrs['class']) ? ' '.e($element->attrs['class'], false) : '');
return ''.$this->nodes($element->children, $ctx).'';
}
if (in_array($element->tag, [...HtmlPolicy::VOID, 'input'], true)) {
return "<{$element->tag}{$attrs} />";
}
// 段落里只有块级模板(目录、mermaid):不包 ,否则