RegExp丶的gravatar头像
RegExp丶 2014-08-13 14:47:51

谁给我解答下牛哥这前端js模板引擎是怎么用的?

谁给我解答下牛哥这前端js模板引擎是怎么用的?

如图,最代码中每个内容页都是生成了静态页,但是静态页中包含了模板,那我访问该页面的时候没有传值,模板里的数据是哪里来的??求解答  20牛币送上


最代码官方编辑于2014-8-13 22:32:06
所有回答列表(2)
最代码官方的gravatar头像
最代码官方  LV167 2014年8月13日

你这牛币明显是要给我的咯。

这是mustache的模板语法,是属于前端的js模板引擎框架,注意不是后端java层的。

参考下这个前后端整合代码吧:bootstrap+jquery+mustache+springmvc+idworker整合demo代码

另外你截图提到的是用户发表评论后,ajax请求评论接口并返回评论对象,最后通过jquery得到mustache的模板再渲染后得到最终结果append到评论列表的尾部。

相关代码如下:

ajax提交评论js代码片断

$('.post_comment').click(function() {
			var post_comment=$(this);
			var id=$(this).attr("id");
			var ids=id.split("__");
			var commentsId=ids[0];
			var type=ids[1];
			var source_id=ids[2];
			var editor=eval("CKEDITOR.instances.editor_"+type+"_"+source_id);
			if(editor.getData()==""){
				alert("请输入评论内容");
				return;
			}
			var template = $('#comment_template').html();
			if ($(this).hasClass('disabled')){
				return;
			}
			post_comment.find("a").text("提交中...").addClass('disabled');
			$.ajax({
				url : "/comment/create.htm",
				type : 'POST',
				dataType : 'json',
				data : {
					content :  editor.getData(),
					type:type,
					source_id:source_id
				},
				success : function(json) {
					if (json.error == "") {
						var html = Mustache.to_html(template, json.comment).replace(/^\s*/mg, '');
						$("#"+commentsId+" .datas").append(html);
						editor.setData("");
						post_comment.find("a").text("评论").removeClass('disabled');
					} else {
						alert(json.error);
					}
				}
			});
	  	});

mustache评论模板js script代码片断

<script id="comment_template" class="template" type='text/template'>
		<div class="data row-fluid">
		    <div class="span1">
		        {{#user}}
		        <a class="name" href="/user/{{id}}.htm" rel="nofollow">
		        <img src="{{avatarUrl}}" alt="{{name}}的gravatar头像"/>
		        </a>
		        {{/user}}
		    </div>
		    <div class="span11">
		        <div class="data_title">
		            {{#user}}<span><a class="name" href="/user/{{id}}.htm" rel="nofollow">{{name}}</a></span>{{/user}}
		            <span class="time pull-right">{{createTimeExt}}</span>
		        </div>
		        <div id="content_{{id}}"  class="content clear">
		            {{{content}}}
		        </div>
		    </div>
		</div>
	</script>

注意:mustache的模板片断也可以用非script来替换,只要用id标示,jquery可以获取得到即可。但是用script有个优势就是搜索引擎会忽略此段代码,如果模板中正好有锚点,比如:

<a class="name" href="/user/{{id}}.htm" rel="nofollow">
		        <img src="{{avatarUrl}}" alt="{{name}}的gravatar头像"/>
		        </a>

这样对seo是很不利的。

官方demo地址:http://mustache.github.io/#demo

其实诸如前端js模板引擎技术有好多

如:

template
官方参考:http://aui.github.io/artTemplate
BaiduTemplate
官方参考:http://baidufe.github.io/BaiduTemplate
juicer
官方参考:http://juicer.name
doT
官方参考:http://olado.github.io/doT
kissy
官方参考:http://docs.kissyui.com和https://github.com/kissyteam/kissy

最后选用mustache还是觉得简单而且确实强大。

评论(4) 最佳答案
RegExp丶的gravatar头像
RegExp丶  LV11 2014年8月13日

说明白了的 再增加20牛币哈   嘿嘿 我是土豪 我怕谁

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友