码迷,mamicode.com
首页 > Web开发 > 详细

使用mustache.js 模板引擎输出html

时间:2016-06-10 00:57:58      阅读:603      评论:0      收藏:0      [点我收藏+]

标签:

MVC Model

技术分享
 public class StudentModel
    {
        [Key]
        public int StuId { get; set; }

        [Display(Name = "姓名")]
        [StringLength(50)]
        [Required(ErrorMessage = "姓名必填")]
        public string StuName { get; set; }
         [StringLength(250)]
        [Display(Name = "住址")]
        [DataType(DataType.MultilineText)]
        //[Required(ErrorMessage = "住址必填")]
        public string Address { get; set; }

        [Display(Name = "年龄")]
        [Required(ErrorMessage = "年龄必填")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
        public int Age { get; set; }
    }
StudentModel

Mvc5WebContext

技术分享
 public class Mvc5WebContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, please use data migrations.
        // For more information refer to the documentation:
        // http://msdn.microsoft.com/en-us/data/jj591621.aspx
    
        public Mvc5WebContext() : base("name=Mvc5WebContext")
        {
        }

        public System.Data.Entity.DbSet<Mvc5Web.Models.StudentModel> StudentModels { get; set; }
    
    }
Mvc5WebContext

 

Controller

技术分享
 public class StudentController : Controller
    {
public JsonResult JsonList()
        {
            //StudentModel stu = new StudentModel { StuId = 100, StuName = "wilson100", Age = 100, Address = "HG" };
            return Json(db.StudentModels, JsonRequestBehavior.AllowGet);
        }
}
View Code

 

html模板

技术分享
<script id="template" type="text/html">
    <table border="1">
        <tr>
            <th>姓名</th>
            <th>地址</th>
            <th>年龄</th>
        </tr>
        {{#studentLists}}
    <tr>
        <td>{{StuName}}
        </td>
        <td>{{Address}}
        </td>
        <td>{{Age}}
        </td>
    </tr>
        {{/studentLists}}
    </table>
</script>
View Code

 

Ajax请求进行客户端模板输出

技术分享
  $("#btnTest").click(function () {
                $.get("JsonList", function (data) {
                    var template = $(‘#template‘).html();
                    Mustache.parse(template);   // optional, speeds up future uses
                    var rendered = Mustache.render(template, { studentLists: data });
                    $(‘#target‘).html(rendered);
                });
            });
View Code

 

mustache.js官方信息

http://mustache.github.io/

https://github.com/janl/mustache.js

使用mustache.js 模板引擎输出html

标签:

原文地址:http://www.cnblogs.com/weiweictgu/p/5573010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!