1. 后端渲染的局限性php
有些时候,咱们总会作一些瀑布流的界面,以下: html
在不断的下拉过程当中,会动态向其中添加剧复的DOM结构,并且,咱们也但愿同步刷新页面的时候,DOM是直接在服务端渲染好的,而并非在客户端再发一次请求去拼装。前端
那么问题就来了,若是咱们须要服务端渲染第一屏的数据,客户端在下拉过程当中,在客户端拼装模板去渲染。那么咱们的模板怎么写,若是后端使用的是NODE的同窗,能够无须担忧,可是若是后端是php+smarty的话,在服务端写的模板,在客户端就无法使用了。git
因而,smartyMonkey应运而生,smartyMonkey的GITHUB地址github
https://github.com/houyu01/smartyMonkey后端
咱们来看一下,smartyMonkey如何帮助咱们解决这个服务端smarty客户端不能用的问题。工具
smartyMonkey使用js写的,能够解析部分smarty语句的库。spa
① 先说一下咱们没有任何编译工具的状况下,最简单的使用例子:code
咱们的创建三个文件:htm
1: item.tpl,里面存放着单条新闻的DOM结构,以下图所示:
2: news.tpl, 里面存放着整张页面的代码。
3:index.js,里面存放着拼装模板的代码。
咱们首先要写item.tpl,在里面,是每条新闻的DOM结构,如:
<li> <h1>{%$title%}</h1> <img src="{%$src%}" /> </li>
咱们在主模板中,引入item.tpl,同步出新闻
引用的方式,在news.tpl中引用模板,并赋值到一个变量中:
<&include file="./item.html" assign="tplStr"&>
在具体引用出,直接调用:
<&include file="string:$tplStr" inline&>
而且,在页面中,把模板传送到前端:
<textarea class="tpl-area" style="display:none;"><&strip&><&$tplStr&><&/strip&></textarea>
在index.js中,咱们直接读取textarea中的模板数据,
<script> var smartyMonkey = window.smartyMonkey var sm = smartyMonkey.create(); var tpl_fn = sm.compile($('.tpl-area').text(), {varnames: ['title', 'src']}); var out = tpl_fn('标题', '图片地址');//装入模板的数据 </script>
因而,咱们就拼合成了要填入页面的模板字符串。这样咱们就达到了,同一个模板(item.tpl),服务端与客户端共用的目的。
若是使用的编译工具的同窗,还能够这样用, 编译的时候,将item.tpl内联到news.tpl中去。
news.tpl中(FIS方式):
<link rel="import" href="./item.html" />
在index.js中:
<script> var smartyMonkey = window.smartyMonkey var sm = smartyMonkey.create(); var tpl_fn = sm.compile(__inline('./item.html'), {varnames: ['title', 'src']}); var out = tpl_fn('标题', '图片地址');//装入模板的数据 </script>
这样写起来,更加容易了。
这就是前端渲染smarty模板解决方案---SmartyMonkey