hkod / frontmatter
一个支持多种格式的上下文感知的前置元数据解析器,采用干净的OOP架构
1.1.0
2018-02-11 13:24 UTC
Requires
- php: >=7.0
Requires (Dev)
- erusev/parsedown: ^1
- mustache/mustache: ^2
- symfony/yaml: >=3, <5
Suggests
- erusev/parsedown: For parsing Markdown
- mustache/mustache: For parsing Mustache templates
- symfony/yaml: For parsing YAML
This package is auto-updated.
Last update: 2024-09-16 11:37:03 UTC
README
一个支持多种格式的上下文感知的前置元数据解析器,采用干净的OOP架构。
前置元数据是位于文件顶部的元数据,通常用分隔行标记包裹,通常为---
。前置元数据可以使用YAML、Json或其他类似的格式进行格式化,如NEON或TOML。
支持的格式
- Json
- INI
- YAML (
require symfony/yaml
) - Markdown (
require erusev/parsedown
) - Mustache (
require mustache/mustache
)
解析器是简单的调用,非常容易添加更多格式。
安装
composer require hkod/frontmatter
用法
一个标准的解析器,具有yaml前置元数据和markdown正文
$parser = new \hkod\frontmatter\Parser( new \hkod\frontmatter\YamlParser, new \hkod\frontmatter\MarkdownParser ); $result = $parser->parse("--- key: value --- This is a **template** "); // value echo $result->getFrontmatter()['key']; // <p>This is a <strong>template</strong></p> echo $result->getBody();
指定前置元数据分隔符
请注意,分隔标记始终代表完整的行。
您可以在创建块解析器时设置分隔符。
$parser = new \hkod\frontmatter\Parser( new \hkod\frontmatter\VoidParser, new \hkod\frontmatter\VoidParser, new \hkod\frontmatter\BlockParser('***', '***') ); $result = $parser->parse("*** frontmatter *** body "); // frontmatter echo $result->getFrontmatter();
将前置元数据放在最后
请注意,由于分隔标记代表一行,最后一行必须以新行(或类似)结束,否则解析器无法识别。
前置元数据 还支持倒置块解析器,其中前置元数据预期放在最后而不是最前面。
$parser = new \hkod\frontmatter\Parser( new \hkod\frontmatter\VoidParser, new \hkod\frontmatter\VoidParser, new \hkod\frontmatter\InvertedBlockParser ); $result = $parser->parse(" This is a the body --- This is the frontmatter --- "); // "This is the frontmatter" echo $result->getFrontmatter();
传递上下文
在解析时,您可以将上下文传递给解析器,然后它将依次传递给所有后续解析器。上下文相关的解析器可以例如扩展模板...
$parser = new \hkod\frontmatter\Parser( new \hkod\frontmatter\VoidParser, new \hkod\frontmatter\MustacheParser ); $context = ['variable' => 'foobar']; $result = $parser->parse("{{variable}}", $context); // foobar echo $result->getBody();
创建复杂的解析器
$parser = (new \hkod\frontmatter\ParserBuilder) ->addFrontmatterPass(new \hkod\frontmatter\MustacheParser) ->addFrontmatterPass(new \hkod\frontmatter\YamlParser) ->addBodyPass(new \hkod\frontmatter\MustacheParser) ->addBodyPass(new \hkod\frontmatter\MarkdownParser) ->setBlockParser(new \hkod\frontmatter\BlockParser('***', '***')) ->buildParser(); $document = "*** key: {{variable}} *** This is a **{{text}}** template "; $context = ['variable' => 'value', 'text' => 'markdown']; $result = $parser->parse($document, $context); // value echo $result->getFrontmatter()['key']; // <p>This is a <strong>markdown</strong> template</p> echo $result->getBody();