首先在cms模版中將html文章轉化為json數據,識別圖片,文本和換行,過濾掉樣式和標簽。這里是用PHP的正則表達式函數來實現的,$content是cms里的html文章。
<?php $_arr = preg_split('/(<img.*?>)/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $_r = array(); foreach($_arr as $_txt) { if(substr($_txt, 0, 4) == '<img') { $_matchs = array(); preg_match('/<img.*?src="(.*?)"/i', $_txt, $_matchs); $_txt = $_matchs[1]; if(preg_match('/^\//', $_txt)) $_txt = $gupload.$_txt; $_r[]= array('type'=>'img', 'data'=>$_txt); }else { $_txt = preg_replace('/&.*?;/', ' ', $_txt); $_txt = preg_replace('/\s+/', ' ', $_txt); $_txt = preg_replace(array('/<br.*?>/i', '/<p.*?>/i', '/<li.*?>/i', '/<div.*?>/i', '/<tr.*?>/i', '/<th.*?>/i'), "\n", $_txt); $_txt = preg_replace('/<.*?>/', '', $_txt); $_r[]= array('type'=>'txt', 'data'=>$_txt); } } $_data = array('title'=> $title, 'info'=> $inputtime, 'content'=> $_r); echo json_encode($_data); ?>
小程序顯示文章時請求cms生成的json數據,並通過循環和模版將文章內容顯示出來。{{content}}是cms模版輸出的json數據,是一條條段落或圖片數據組成的數組。
<template name="img"> <view> <image class="content-img" mode="aspectFit" src="{{item.data}}"></image> </view> </template> <template name="txt"> <view> <text>{{item.data}}</text> </view> </template> <view class="content"> <block wx:for="{{content}}"> <template is="{{item.type}}" data="{{item}}"/> </block> </view>
