使用mustache.js 模板引擎输出html
Posted 漂泊雪狼的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用mustache.js 模板引擎输出html相关的知识,希望对你有一定的参考价值。
看了https://mustache.github.io/你就知道mustache是非常强大的模板引擎,支持多种语言,下面是个简单入门例子:
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; } }
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; } }
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); } }
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>
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); }); });
mustache.js官方信息
以上是关于使用mustache.js 模板引擎输出html的主要内容,如果未能解决你的问题,请参考以下文章
Twitter typeahead.js:可以使用 Angular JS 作为模板引擎吗?如果不是,我该如何替换 Hogan/Mustache js 的“”?