如何识别和删除段落说明
在 DokuWiki 中,段落由两个特定的指令表示:
p_open
- 打开一个段落p_close
- 结束段落
遍历指令时,您可以检查这些指令类型并跳过它们:
// Get instructions
$instructions = p_get_instructions($text);
// Create a filtered set of instructions
$filteredInstructions = [];
foreach ($instructions as $instruction) {
// Skip paragraph open/close instructions
if ($instruction[0] === 'p_open' || $instruction[0] === 'p_close') {
continue;
}
// Keep all other instructions
$filteredInstructions[] = $instruction;
}
// Use the filtered instructions
$renderer->nest($filteredInstructions);
插件的 Render 方法中的示例
这是一个更完整的示例,展示了如何在插件的方法中实现这一点:render()
public function render($mode, Doku_Renderer $renderer, $data) {
if ($mode !== 'xhtml') return false;
// Get instructions from the data
$instructions = p_get_instructions($data['text']);
// Filter out paragraph tags
$filteredInstructions = [];
foreach ($instructions as $instruction) {
if ($instruction[0] === 'p_open' || $instruction[0] === 'p_close') {
// Skip paragraph instructions
continue;
}
$filteredInstructions[] = $instruction;
}
// Create a temporary renderer to process the filtered instructions
$tempRenderer = new Doku_Renderer_xhtml();
// Process the filtered instructions
foreach ($filteredInstructions as $instruction) {
if (method_exists($tempRenderer, $instruction[0])) {
call_user_func_array([$tempRenderer, $instruction[0]], $instruction[1] ?: []);
}
}
// Add the result to the original renderer
$renderer->doc .= $tempRenderer->doc;
return true;
}
使用 nest() 方法
或者,您可以使用专为执行指令设计的方法:nest()
public function render($mode, Doku_Renderer $renderer, $data) {
if ($mode !== 'xhtml') return false;
// Get instructions
$instructions = p_get_instructions($data['text']);
// Filter out paragraph tags
$filteredInstructions = array_filter($instructions, function($instruction) {
return $instruction[0] !== 'p_open' && $instruction[0] !== 'p_close';
});
// Use the filtered instructions
$renderer->nest(array_values($filteredInstructions));
return true;
}
重要注意事项
- 文档结构:删除段落标签可能会影响文档结构。确保生成的 HTML 仍然有效。
- 嵌套内容:如果内容位于段落内,则它现在将直接位于父容器中,这可能会更改样式或行为。
- 渲染器兼容性:不同的渲染器可能会以不同的方式处理段落标签的缺失。使用插件支持的所有渲染器进行测试。
- 缓存影响:修改指令可能会影响缓存。考虑为您的插件禁用缓存:
$renderer->info['cache'] = false;
来自 DokuWiki 代码库的示例
看看 DokuWiki 在渲染阶段如何处理指令:parserutils.php:688-693
你可以看到 DokuWiki 通过调用渲染器上的相应方法来执行每条指令。通过在指令到达这一点之前过滤它们,你可以有效地删除段落标签。
同样,该方法遵循相同的模式:renderer.php:136-144nest()
笔记
通过在渲染阶段过滤说明,可以删除段落标签。但是,请注意,这可能会影响文档结构和样式。始终进行全面测试,以确保您的更改在不同的渲染器和内容类型中产生预期的输出。
如果你在插件中实现它,请考虑对文档结构的更广泛影响,并确保生成的 HTML 仍然有效且格式正确。