模版设计.md 2.0 KB

文章内模版设计方案

需求

在用户编辑的markdown文档内嵌入自定义模版。支持术语显示,注释,文章引用,声明等可重用内容。

markdown 文档内容:

# 标题

{{term|citta}}
{{term|word=citta}}

解决方案

使用 https://mustache.github.io/ 。由于mustache不支持自定义函数。所以绕道,用mustache 的 helper 拿到用户输入的参数后再次用mustache进行渲染。

https://github.com/bobthecow/mustache.php/wiki#helpers

第一步

用户输入的markdown 文本。 用正则替换

[[citta]]->{{term|citta}}
搜索
\{\{(.+?)\}\}
替换为
\n{{#function}}\n$1\n{{/function}}\n
{{term|citta}}
就变成
{{#function}}
term|citta
{{/function}}

第二步 准备模版文件

这个其实是放数据库里的

term.tpl

<term word='{{word}}'>
<span class='word'>{{word}}</span>
(<span class='meaning'>{{meaning}}</span>)
</term>

第三步 解析{{#function}}

用helper 解析{{#function}} 里面的内容。拿到模版名称和参数。并再次用Mustache 和对应的模版文件以及参数渲染html字符串 需要预处理,得到这个文章里面用的模版名称(函数名)列表。

$tpl-list=["term"=>"term.tpl的内容"];
$m = new Mustache_Engine(array('entity_flags' => ENT_QUOTES));
$m->render($tpl, array(
  'function' => function($text) use($m,$tpl-list) {
    1: 使用url函数解析path
    $param = explode("|",$text);
    3: 处理业务逻辑
    switch([param[0]){
        case 'term':
            //获取实际的参数
            $tplParam = Term::where("word",param[1])->first();
        case 'article':
            $tplParam = Article::where("uid",param[1])->first();
        default:
            $tplParam['p1'] = param[1];
        break;
    }
    4: 返回拼好的字符串
    $html = $m->render($tpl-list[param[0]], $tplParam)
    return $html;
  }
)); 

模版

{{inlinenote|note content}}

{{q|sn.a. 2|3|2}} {{q|137|45}}

{{article|122342234324}}