最近領導讓我研究一下微信小程序,將cms裏的文章顯示到微信小程序裏。本以爲是個簡單的功能,但看了微信的開發文檔之後才發現小程序不能解析html文檔,也不支持跳轉到web頁面。微信小程序我就不多介紹了官方文檔和網上的討論很多,在這裏貼一下我實現小程序顯示cms文章的方法。
由於小程序不支持html解析,所以我們只能修改cms的文章模版,將文章內容轉化爲json數據輸出,然後再在小程序裏用js解析json並做出相應顯示。
小程序不支持a標籤,在小程序中也不適宜帶入花哨的樣式,所以我修改cms模版,將html中的樣式和a標籤都去掉,只留下文字,換行和圖片數據,在小程序中將分段文字和圖片顯示爲<view>和<image>
首先在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>