2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

Handlebars模板引擎之上手

handlebars


Handlebars,一个JavaScript模板引擎,是基于Mustache的扩展。模板引擎的都存在一个上下文环境,这是它的作用区间。

需求:基本使用


需要的库

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.js"></script>

使用

这里是通过ajax请求后端,并返回json数据,填充到模板中,并渲染出select。

html

 <div class="form-group">
      <label for="onestair" class="col-md-5 control-label label-font">一级广告位:</label>
      <div class="col-md-7 onestair">
                
      </div>
</div>

<!--
...省略无关部分
-->


<!--handlebars模板部分-->
<script id="onestair-template" type="text/x-handlebars-template">
    <select id="onestair" class="form-control" data-live-search="true">
        <option value='all'>全部</option>
        {{#each this}}
        <option value="{{this.onestair}}">{{ this.onestair }}</option>
        {{/each}}
    </select>
</script>

js

$.get(window.stnt_hosts + 'thirdAdmanage/onestair', function(data, status) {
			var myTemplate = Handlebars.compile($("#onestair-template").html());			
			$('.onestair').html(myTemplate(data));
			$('#onestair').selectpicker({
				size: 5
			});
		})
//返回的json格式如下
[{id: 1, onestair: "01", twostair: "A01", onestair_name: "顶部AXCCC", twostair_name: "顶部-右边BXX",…}]
			    

这里通过##Handlebars.compile($("#onestair-template").html())##取出我们的模板代码。

遍历/循环

注意这里的script标签的id,还有type类型。最重要的是遍历部分

 {{#each this}}
     <option value="{{this.onestair}}">{{ this.onestair }}</option>
 {{/each}}

使用each 来遍历,并且要闭合标签{{/each}}。

其中取值也是通过对象的形式,this指的是当前一条的数据对象。

最终效果

posted on 2017-02-27 10:15  qize  阅读(784)  评论(0编辑  收藏  举报

导航