您的位置:首页 > 移动开发 > 微信开发

微信小程序显示cms里的html文章

2016-12-20 10:22 211 查看
最近领导让我研究一下微信小程序,将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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: